gpt4 book ai didi

javascript - 为什么过滤新的 JSON 对象会导致旧对象 self 更新?

转载 作者:行者123 更新时间:2023-11-30 07:45:27 25 4
gpt4 key购买 nike

我有一个名为 arr 的 JSON 数组和一个从 arr 创建的名为 new_arr 的新数组。

var arr = {"data":
[
{"name":"Alan","height":"171","weight":"66"},
{"name":"Ben","height":"182","weight":"90"},
{"name":"Chris","height":"163","weight":"71"}
]
};

var new_arr = arr;

new_arr.data = jQuery.grep(new_arr.data, function(n, i){
return n.weight > 70;
});

数组 arrnew_arr 都变成:

{"data":
[
{"name":"Ben","height":"182","weight":"90"},
{"name":"Chris","height":"163","weight":"71"}
]
};

我的问题是:“为什么修改新数组会改变旧数组?

最佳答案

没有新数组。它只是对旧数组的新引用。
在另一个例子中尝试:

var a = {};
var b = a;
// check to see if they are equal
alert(a === b);
// modify one of them
b.foo = 'bar';
// check to see if they are equal
alert(a === b);
// modify one of them
a.bar = 'foo';
// check to see if they are equal
alert(a === b);

ab 引用同一个对象,因此,当您修改 a 时,您也修改了 b等等。

如果你使用 jquery,你应该使用 extend 方法:

var new_arr = $.extend(true,arr);

关于javascript - 为什么过滤新的 JSON 对象会导致旧对象 self 更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7501226/

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