【发布时间】:2015-10-11 14:25:18
【问题描述】:
我有一个对象数组和一个forEach(),就像这个:
$scope.things = [
{x: 2},
{x: 4},
{x: 5}
];
angular.forEach($scope.things, function(thing) {
//Pick one of the lines at a time
//thing.x += 10; // <--- works
//thing.k = thing.x + 1; // <--- works
//thing = {k: thing.x + 10, o: thing.x - 1}; // <--- doesn't work
//
});
console.log($scope.things);
我的意思是"works", "works" and "doesn't work":
-
x加了 10,最终数组看起来像{x: 12}, {x: 14}, {x: 15} -
k已创建,最终数组看起来为{x: 2, k: 3}, {x: 4, k: 5}, {x: 5, k: 6} -
thing本身并没有被替换,things的数组看起来一模一样。
我的问题是:
- 为什么会这样?
- 这是预期的行为吗?
- 如何完全替换每个
thing?
【问题讨论】:
-
查看这篇文章:stackoverflow.com/questions/12482961/… ...它有你正在寻找的所有答案。
-
@Mindastic - 是的。即使我在下面写下我的答案,我心里想,“这肯定是重复的。这里一定已经有答案了。”感谢您找到它。
标签: javascript arrays angularjs