javascript - 循环遍历数组并且只获取最后一项?
问题描述
我正在尝试使用 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>
解决方案
所以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();
推荐阅读
- ansible - 如何使用随机 6 位密码创建用户记录并使用 Ansible playbook 将密码设置保存在文件中
- c# - 为什么我的 C# 端点不理解我的 Angular Reactive 表单数据?
- typescript - 有没有办法在泛型参数中使用条件“类型保护”类型?
- sqlalchemy - Python Mock Patch 两个相似的函数
- javascript - 摆脱 ReactJS 的重复代码
- c# - 如何将值设置为只读 Httpcontex.request.HttpMethod?
- r - 将 eval(parse()) 应用于 r 中列的所有行
- python - 如何使用 groupby 为 Dataframe 中的每个组创建重复索引?
- python - 如何对图像的所有像素值求和 100?
- javascript - 打开文件时运行的脚本/插件 - 与代码