javascript - 在 forEach 数组中使用 for 循环

标签 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}

我做错了什么?

谢谢。

最佳答案

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

相关文章:

java - 在java中无法将数组作为参数传递

javascript - 如何检查包含子数组的数组的大小?

javascript数组比较循环多次

java - 这些 "for"循环有什么作用?

c# - Foreach 循环 - 长字符串的性能

javascript - 如何根据 localStorage 中是否有条目来设置对象中的值?

javascript - 在 VueJS 组件中引用静态资源

php - 未进入 foreach 循环

javascript - 音频播放特定时间后显示警报

javascript - 如何在不使用 void 的情况下重新启动 CSS 动画?