如何更新angular.forEach()中的当前值?

时间:2015-05-14 00:38:56

标签: javascript angularjs

我试图将对象的一部分值从整数值1或0转换为布尔值true或false。

结构如下:

angular.forEach(a.b.c, function (options) {
    ...
    angular.forEach(options, function (value, option) {
        if (value == 0) {
            option = false;
        } else {
            option = true;
        }
        console.log(option + " = " + value);  // This shows correct results;
    }
}
console.log(a.b.c) // when navigating to the options, the options have not changed from their integer values.

我错过了什么?

1 个答案:

答案 0 :(得分:8)

您只是将局部变量的值更改为false / true,而不是更改对象的值。



var array = [{
  key: 1
}, {
  key: 0
}];
angular.forEach(array, function(options) {
  angular.forEach(options, function(value, option) {
    if (value == 0) {
      options[option] = false;
    } else {
      options[option] = true;
    }
    //the if else can be simplified to
    //options[option] = value != 0;
    console.log(option + " = " + options[option]);
  })
})

console.log(array);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
&#13;
&#13;
&#13;

如果您知道要更新的密钥,那么

&#13;
&#13;
var array = [{
  key: 1
}, {
  key: 0
}];
angular.forEach(array, function(options) {
  options.key = options.key != 0;
})

console.log(array);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
&#13;
&#13;
&#13;