我正在尝试将对象值的一部分从整数值 1 或 0 转换为 bool 值 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.
我错过了什么?
最佳答案
您只是将局部变量的值更改为 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>
如果你知道要更新的 key
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>
关于javascript - 如何更新 angular.forEach() 中的当前值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30227484/