0
我有对象的数组和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
?
检查这个帖子:http://stackoverflow.com/questions/12482961/is-it-possible-to-change-values-of-the-array-when-doing-foreach-in-javascript。 ..它有你正在寻找的所有答案。 – Mindastic
@Mindastic - 是的。就在我在下面写下我的答案时,我心想:“这肯定是重复的,这里肯定有答案。”感谢您找到它。 – gilly3