在forEach数组中使用for循环

时间:2015-02-20 13:39:50

标签: javascript arrays foreach

请看下面的代码。

我有一个主阵列: 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}

我做错了什么?

谢谢。

4 个答案:

答案 0 :(得分:1)

只需删除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));

答案 1 :(得分:0)

在使用forEach进行循环时,如果标题不是当前值,则第二个循环的更改会删除第一个循环中的更改,因为其他情况会将isSelect设置为 false 。 / p>

您应该检查for block中的isSelected 是否,并跳过标题等于值部分。

答案 2 :(得分:0)

对于每种颜色,由于&#34; else&#34;首先将它们设置为false然后循环并设置您想要的那些

        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/

答案 3 :(得分:0)

你在其他部分做出了无与伦比的错误。因此,只更新最后一个,然后不更改。删除其他部分。