在 forEach 数组中使用 for 循环

Using for loop inside forEach array

请看下面的代码。

我有一个主数组:nop 和一个临时数组:tempArray

如果 tempArray 数组包含主数组 nop 中的元素,则将其 isSelect 标记为 true。

但是,如果您 运行 下面的代码,您将只看到 tempArray 的最后一个元素在主数组 nop 上被更改....

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));

当使用 forEach 循环时,第二个循环会删除第一个循环的更改,因为如果标题不是,则将 isSelect 设置为 false当前值。

您应该在您的 for 块中检查 isSelected 是否 true 并跳过 title equals value 部分。

由于 "else" 首先将它们全部设置为 false 然后循环并将您想要的那些设置为 true

,因此对于每种颜色您都将覆盖之前的结果
        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);
                }

            }
        });

js fiddle - http://jsfiddle.net/rxq529s4/

您在 else 部分将不匹配的设为假。所以,只有最后一个被更新,然后没有改变。删除else部分。