请看下面的代码。
我有一个主数组:nop 和一个临时数组:tempArray
如果 tempArray 数组包含主数组 nop 中的元素,则将其 isSelect 标记为 true。
但是,如果您运行下面的代码,您将只看到主数组 nop 上已更改的 tempArray 的最后一个元素....
var nop = [
{title:'blue', isSelect: false },
{title:'red', isSelect: true },
{title:'yellow', isSelect: false },
{title:'black', isSelect: false },
{title:'dark blue', isSelect: false },
{title:'reddish', isSelect: false },
{title:'hello', isSelect: false },
{title:'help', isSelect: false },
{title:'me', isSelect: false }
];
var tempArray = ["blue", "hello", "help"];
tempArray.forEach(function(value){
var index;
for (index = 0; index < nop.length; ++index) {
if (nop[index].title === value){
nop[index].isSelect = true;
console.log('FOR LOOP = TRUE for: ' + value);
}
else {
nop[index].isSelect = false;
}
}
});
console.log(JSON.stringify(nop));
以上结果:
FOR LOOP = TRUE for: blue
FOR LOOP = TRUE for: hello
FOR LOOP = TRUE for: help
[{"title":"blue","isSelect":false},{"title":"red","isSelect":false},{"title":"yellow","isSelect":false},{"title":"black","isSelect":false},{"title":"dark blue","isSelect":false},{"title":"reddish","isSelect":false},{"title":"hello","isSelect":false},{"title":"help","isSelect":true},{"title":"me","isSelect":false}]
只有这个元素被更新:{"title":"help","isSelect":true}
我想更新所有 3 个元素:
{"title":"blue","isSelect":true}
{"title":"yellow","isSelect":true}
{"title":"help","isSelect":true}
我做错了什么?
谢谢。
最佳答案
只需删除else
条件
tempArray.forEach(function(value){
var index;
for (index = 0; index < nop.length; ++index) {
if (nop[index].title === value){
nop[index].isSelect = true;
console.log('FOR LOOP = TRUE for: ' + value);
}
}
});
工作 Fiddle
编辑
for (index = 0; index < nop.length; ++index)
if (tempArray.indexOf(nop[index].title))
nop[index].isSelect = true;
console.log(JSON.stringify(nop));
关于javascript - 在 forEach 数组中使用 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28630341/