gpt4 book ai didi

javascript - javascript中嵌套数组和引用的副本

转载 作者:行者123 更新时间:2023-11-30 13:21:23 25 4
gpt4 key购买 nike

以下 javascript 代码 [ jsfiddle ]:

Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};

var masterlist = [{
name: "Master1"},
{
name: "Master2"}];
var parentlist = [{
name: "Parent1"},
{
name: "Parent2"}];
var childlist = [{
name: "Child1"},
{
name: "Child2"}];

for (var i = 0; i < masterlist.length; i++) {
var master = masterlist[i];
master.parents = parentlist.slice();
for (var j = 0; j < master.parents.length; j++) {
var parent = master.parents[j];
parent.children = childlist.slice();
}
}

console.log("before removing")
console.log("master1 parents: " + masterlist[0].parents.length);
console.log("master2 parents: " + masterlist[1].parents.length);
console.log("master1 parent 1 childrens: " + masterlist[0].parents[0].children.length);
console.log("master2 parent 2 childrens: " + masterlist[1].parents[1].children.length);

masterlist[0].parents.remove(0);
masterlist[0].parents[0].children.remove(0);

console.log("after removing")
console.log("master1 parents: " + masterlist[0].parents.length);
console.log("master2 parents: " + masterlist[1].parents.length);
console.log("master1 parent 1 childrens: " + masterlist[0].parents[0].children.length);
console.log("master2 parent 2 childrens: " + masterlist[1].parents[1].children.length);?

结果:

before removing
master1 parents: 2
master2 parents: 2
master1 parent 1 childrens: 2
master2 parent 2 childrens: 2
after removing
master1 parents: 1
master2 parents: 2
master1 parent 1 childrens: 1
master2 parent 2 childrens: 1

我期望(并且需要)这个:

before removing
master1 parents: 2
master2 parents: 2
master1 parent 1 childrens: 2
master2 parent 2 childrens: 2
after removing
master1 parents: 1
master2 parents: 2
master1 parent 1 childrens: 1
master2 parent 2 childrens: 2 <-- difference

我做错了什么?看起来 children 指的是同一个数组,我也对初始的 child 数组进行了切片(它确实按预期与父数组一起工作)。

最佳答案

看看http://de.selfhtml.org/javascript/objekte/array.htm#slice可以提供一个潜在的答案(由我完成翻译):

“请注意:如果数组中包含一个对象,则新创建的数组包含对该对象的引用。这意味着:如果更改了对象,则使用 slice() 创建的数组也会更改。如果包含数字和字符串,它们被复制。”

应该解释为什么两者都会改变,不是吗?

关于javascript - javascript中嵌套数组和引用的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153831/

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