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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30227484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:55:33  来源:igfitidea点击:

How to update current values inside an angular.forEach()?

javascriptangularjs

提问by Raphael Rafatpanah

I am trying to convert a portion of an object's values from integer values 1 or 0 to boolean values true or false.

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

The structure is as follows:

结构如下:

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.

What am I missing?

我错过了什么?

回答by Arun P Johny

You are just changing the value of the local variable to false/true, not changing the value of the object.

您只是将局部变量的值更改为 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>

If you know the key to be updated then

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

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

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