Copy an array without linking to it
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | var ProtVar = function(arr){ this.gr1 = []; this.gr2 = []; this.arr = arr; return this; } ProtVar.prototype.setArrs = function(){ this.gr1 = this.arr; this.gr2 = this.arr; return this; } ProtVar.prototype.shiftGr1 = function(){ this.gr1.shift(); return this; } ProtVar.prototype.showData = function(){ console.log("gr1 =", this.gr1.length, this.gr1); console.log("gr2 =", this.gr2.length, this.gr2); console.log("arr =", this.arr.length, this.arr); return this; } var protVar = new ProtVar([1,2,3,4]).setArrs().shiftGr1().showData(); |
如何在不链接到同一数组的情况下复制该数组?
我知道如何使用
1 2 3 4 5 | ProtVar.prototype.setArrs = function(){ this.gr1 = this.arr.slice(0); this.gr2 = this.arr.slice(0); return this; } |
这是正确的方法吗?
There are at least 4 (!) principal ways to clone an array:
- loop
- constructor
- slice / splice
- concat
请看这个答案