首页 > 解决方案 > 循环遍历数组并且只获取最后一项?

问题描述

我正在尝试使用 javascript 循环遍历我的背景颜色,但它只返回最后一项,蓝色。

我试图在这个网站上查看不同的答案,但我是 javascript 新手,无法理解他们在说什么。有人有答案吗?

function background() {
  const bg = document.querySelector('header');
  const colors = ['red', 'orange', 'yellow', 'blue'];

  for (let i = 0; i < colors.length; i++) {
    console.log(colors[i])
    bg.style.backgroundColor = colors[i];
  }
}

background();
setInterval(background, 5000);
<header style="width:100px; height:100px"></header>

标签: javascriptarraysloops

解决方案


所以console.log打印出所有这些,但只有最后一个仍然保存?

因为您在循环内覆盖它,并且循环运行就像立即(或者非常非常快,你无法通过肉眼发现)。意思是,因为有一个 for 循环,所以setInterval根本没有做任何事情。

实际发生了什么:

  • 你没有做: 1,等待 5 秒,2,等待 5 秒等。
  • 相反,你正在做: 1234,等待 5 秒,1234,等待 5 秒等。

让我们看一下代码中的示例解决方案:

let i = 0;
// move variable i out of the function
// so it is not reset every time the function is run

function background () {
    // your code, nothing new here
    const bg = document.querySelector('header');
    const colors = ['red', 'orange', 'yellow', 'blue']
    bg.style.backgroundColor = colors[i];

    // then to have it change
    if (i < (colors.length) { i++; } // increase i+1 until we have reached max
    // i++ is shorthand for i = i + 1
    else i = 0;
    // and if have, reset it (that's why it is outside the function)
    // if it were inside it, it would reset every time the function runs
}
setInterval(background, 5000);
background();

推荐阅读