【问题标题】:Replacing objects inside Angular's forEach() [duplicate]替换Angular的forEach()中的对象[重复]
【发布时间】: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


【解决方案1】:

为什么会这样?

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

这是预期的行为吗?

是的

我怎样才能完全替换每个thing

如果你想改变一个对象的属性值,你只需要这样做。进行分配时引用对象及其属性名称。 The forEach iterator function 通过 valuekeyobj。所以,你可以说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!
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2016-05-22
    • 2020-10-31
    • 2015-10-08
    相关资源
    最近更新 更多