【问题标题】:Strange Javascript Variable Function Scope With Loop [duplicate]带有循环的奇怪的Javascript变量函数范围[重复]
【发布时间】:2019-06-07 06:11:04
【问题描述】:

我在尝试执行以下操作时遇到了一些奇怪的行为:

  1. 创建基础 JSON 对象
  2. 创建一个 for 循环并将基础对象发送到要修改的新函数
  3. 新函数应修改基本 JSON 对象的一个​​元素,然后将其发回

这是我的示例代码:

var object = [
{"test": "Test1", "id": 0},
{"test": "Test2", "id": 0},
{"test": "Test3", "id": 0},
{"test": "Test4", "id": 0},
];


for(var i=0; i < 4; i++) {
newObject(i).then(function(obj){
  console.log(obj);
  })
}

function newObject(i) {
  return new Promise(function(resolve, reject){
  var newObject = object;
  newObject[i].id = i;
    resolve(newObject);
  })
}

我希望从 console.log(obj) 收到的是 4 倍这样的不同对象

[
   {"test": "Test1", "id": 0},
   {"test": "Test2", "id": 0},
   {"test": "Test3", "id": 0},
   {"test": "Test4", "id": 0},
];

[
   {"test": "Test1", "id": 0},
   {"test": "Test2", "id": 1},
   {"test": "Test3", "id": 0},
   {"test": "Test4", "id": 0},
];

[
   {"test": "Test1", "id": 0},
   {"test": "Test2", "id": 0},
   {"test": "Test3", "id": 2},
   {"test": "Test4", "id": 0},
];

[
   {"test": "Test1", "id": 0},
   {"test": "Test2", "id": 0},
   {"test": "Test3", "id": 3},
   {"test": "Test4", "id": 0},
];

但是我最终收到的是像这样完全相同的对象的 4 倍

[
   {"test": "Test1", "id": 0},
   {"test": "Test2", "id": 1},
   {"test": "Test3", "id": 2},
   {"test": "Test4", "id": 3},
];

【问题讨论】:

  • 注意:不存在 JSON 对象之类的东西。
  • 另外,var newObject 不是初始对象的副本,它是对它的引用。每个循环都在更改同一个对象。
  • 查看如何克隆对象数组。 stackoverflow.com/questions/597588/…

标签: javascript for-loop javascript-objects


【解决方案1】:

您的问题是在您的 Promise 函数中,您引用的是相同的对象,而不是创建克隆。

var newObject = object; // this is a reference, not a copy/clone

相反,您需要创建object 数组的深层克隆。 在单行中执行此操作的一种方法是使用 JSON:

var newObject = JSON.parse(JSON.stringify(object));

更好的方法是:

var newObject = object.map(({test, id}) =&gt; ({test, id}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2013-08-30
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2014-11-10
    相关资源
    最近更新 更多