对于具有其他值的元素,如何将数组元素的值设置为true?

时间:2015-01-21 10:04:20

标签: javascript

我有一个名为test的对象数组。

使用现代浏览器,我可以轻松找到该数组中的元素,并将testId设置为99并设置该元素current 字段为真?

如果可能的话,我想避免每次循环之类的事情,但我不确定能做什么。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

var test = [ {"testId" : 99, "current" : false }, {"testId" : 10, "current" : false }];

test.forEach(function(r) {
    if (r.testId == 99) {
        r.current = true;
    }
});

不确定为什么要避免循环,也不清楚你的问题是否要为满足条件的所有元素(上面的代码当前所做)或在第一个之后中断。

JS Fiddle

答案 1 :(得分:1)

var found = test.filter(function( obj ) {
  return obj.testId == 99;
})[0];
if (found) found.current = true;