小能豆

如何让我的代码循环遍历这个数组?

javascript

我正在尝试制作一个颜色变换器,我希望程序循环遍历数组,每次单击都将颜色一一更改,然后将颜色代码类更新为数组的名称,我还没有实现这一点因为我想首先解决这个最初的问题。到目前为止,它仅将颜色更改为最后一个索引。

const colorArray = ["blue", "green", "red", "orange", "violet", "indigo", "yellow", "white", "pink", "black"];

function changeColor() {
    const body = document.querySelector('body');
    const bodyColor = body.style.backgroundColor;
    const colorCode = document.querySelector('color-code');
    const button = document.querySelector('button');

    button.addEventListener('click', function () {
        for(let i = 0; i < colorArray.length; i++) {
            body.style.backgroundColor = colorArray[i];
        }


    })
}

changeColor();

我尝试使用 for 循环,我不太确定这是正确的方法。


阅读 96

收藏
2024-02-27

共1个答案

小能豆

正在循环遍历数组。结果是最后一个值保持设置。

听起来您不想循环遍历数组,而是想跟踪数组的当前索引并在每次单击时使用“下一个”索引。像这样的东西:

const colorArray = ["blue", "green", "red", "orange", "violet", "indigo", "yellow", "white", "pink", "black"];
let currentIndex = 0;

const body = document.querySelector('body');
const button = document.querySelector('button');

function changeColor() {
  // set the color to the current array index, and increment the index
  body.style.backgroundColor = colorArray[currentIndex++];

  // if the current index exceeds the array, reset it
  if (currentIndex >= colorArray.length) {
    currentIndex = 0;
  }
}

button.addEventListener('click', changeColor)

changeColor();
2024-02-27