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

标签 javascript angularjs

我正在尝试将对象值的一部分从整数值 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/

相关文章:

javascript - 如何在 blogspot 中编码 javascript?

javascript - 动态设置 ng-model 被破坏

javascript - 绑定(bind)到 Date() 对象时如何格式化 input[time] 的值

javascript - javascript中的回调解释

javascript - 为什么 `.innerText` 属性在 Firefox 中不起作用?

javascript - Angularjs - 将服务数据绑定(bind)到许多 Controller 中的模型

javascript - Mootools提交表单仅在通过id选择表单时有效

javascript - 使用 Jasmine 对位于不同模块中的两个服务进行单元测试

javascript - 转换后无法访问对象方法

javascript - 未捕获的引用错误 :. jspdf 未定义