📜  正向和反向循环一一js - Javascript代码示例

📅  最后修改于: 2022-03-11 15:02:48.487000             🧑  作者: Mango

代码示例1
var arr = ['red', 'blue', 'black', 'green'];
var currentIndex = 0;

var nextBtn = document.getElementById('nextBtn');
var prevBtn = document.getElementById('prevBtn');

nextBtn.addEventListener('click', nextItem);

prevBtn.addEventListener('click', prevItem);

function nextItem() {
  if (currentIndex === (arr.length - 1)) {
    return;
  }
  
  console.log(
    arr[++currentIndex]
  );
}

function prevItem() {
  if (currentIndex === 0) {
    return;
  }
  
  console.log(
    arr[--currentIndex]
  );
}