1

以下 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);?

结果是:

移除
master1 父母之前:2
master2 父母:2
master1 父母 1 孩子:2
master2 父母 2 孩子:2
移除
master1 父母:1
master2 父母:2
master1 父母 1 孩子:1
master2 父母 2 孩子:1

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

删除
master1 父母之前:2
master2 父母:2
master1 父母 1 孩子:2
master2 父母 2 孩子:2
移除
master1 父母后:1
master2 父母:2
master1 父母 1 孩子:1
master2 父母 2 孩子:2 <-- 差异

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

4

1 回答 1

3

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

"Please note: If there is an object contained within the array, the newly created array contains a reference to that object. That means: If the object is changed, so does the array that was created using slice(). If numbers and strings are contained, they are copied."

Should explain why both change, shouldn't it?

于 2012-04-14T22:48:22.243 回答