2015-07-21 121 views
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
+0

检查这个帖子:http://stackoverflow.com/questions/12482961/is-it-possible-to-change-values-of-the-array-when-doing-foreach-in-javascript。 ..它有你正在寻找的所有答案。 – Mindastic

+0

@Mindastic - 是的。就在我在下面写下我的答案时,我心想:“这肯定是重复的,这里肯定有答案。”感谢您找到它。 – gilly3

回答

1

为什么会发生这种情况?

因为thing只是一个变量。您可以将变量的值(即使是参数变量)重新分配给您想要的任何内容,而不会影响对象的值。

这是预期的行为?

我怎么能完全取代每个thing

如果要更改对象属性的值,则需要这样做。在进行作业时引用对象及其属性名称。 The forEach iterator function通过value,keyobj。所以,你可以说obj[key] = { whatever: "you want" }更改属性值。

angular.forEach($scope.things, function(thing, key, things) { 

    //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 

    //things[key] = {k: thing.x + 10, o: thing.x - 1}; // <--- works! 
});