gpt4 book ai didi

javascript - 将多级对象文字插入数组时,值困惑

转载 作者:行者123 更新时间:2023-11-28 01:06:25 25 4
gpt4 key购买 nike

我有一个具有多个级别的 json 对象,我们将其称为 ZOO。

var ZOO = {
info: {
cages: {
amount: 5,
size: { x: 1, y: 0.2 },
additionals: 'a broken bucket',
},
},
}, myZoos = [];

现在我想克隆并更改此对象,然后将其添加到名为 myZoos 的数组中。

window.JSON.clone = function (json) {
return $.extend({}, json);
};
for (var a = 1; a <= 3; a++) {
var newZoo = JSON.clone(ZOO);
newZoo.info.cages.size = { x: (a * 5), y: (a * 2) };
myZoos.push(newZoo);
}

让我们读取填充的数组并检查随机大小值!

for (var b = 0; b < myZoos.length; b++) {
var myZoo = myZoos[b];
console.log(myZoo.info.cages.size);
}

结果:

Object { x: 15, y: 6 }
Object { x: 15, y: 6 }
Object { x: 15, y: 6 }

看起来我只获得了推送到数组的最后一个值!
为什么只返回数组中的最后一项?

最佳答案

需要使用.extend() method的深拷贝参数

window.JSON.clone = function (json) {
return $.extend(true, {}, json);
};

关于javascript - 将多级对象文字插入数组时,值困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25025629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com