我在尝试执行以下操作时遇到一些奇怪的行为:
- 创建基础 JSON 对象
- 创建一个 for 循环并将基础对象发送到要修改的新函数
- 新函数应修改基本 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},
];
最佳答案
您的问题是,在 Promise 函数内,您引用相同的对象,而不是创建克隆。
var newObject = 对象;//这是一个引用,而不是副本/克隆
相反,您需要创建 object
数组的深层克隆。
一种简单的方法是使用 JSON:
var newObject = JSON.parse(JSON.stringify(object));
更好的方法是:
var newObject = object.map(({test, id}) => ({test, id}));
关于javascript - 奇怪的 Javascript 变量函数作用域与循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54161462/