2015-07-21 94 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! 
});