下面的JavaScript代碼[jsfiddle]:副本以JavaScript
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兒童:1
master2父母:2
master1父1名兒童:1個
master2父2名兒童:2
去除
master1父母后2 < - 差異
我在做什麼錯? 它看起來像孩子們指的是相同的數組,我也沒有切片的初始兒童數組(它按照預期與父數組一起工作)。
爲什麼不使用'.splice()'從現有數組中刪除元素? – jfriend00 2012-04-14 13:05:25
這不能解決原來的問題。考慮masterlist [0] .parents [0] .children.push({name:「child3」});兩者都再次更新。 – 2012-04-14 13:46:11
這將是很好的知道你想要做什麼總體與這個腳本。 Jus粘貼代碼和期望的輸出不能幫助我們讀取代碼 – Tamil 2012-04-14 17:13:09