0
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();

How should I copy the array without linking to the same array?

I figured out how to do this with slice(0); see below.

ProtVar.prototype.setArrs = function(){
    this.gr1 = this.arr.slice(0);
    this.gr2 = this.arr.slice(0);
    return this;
}

Is this the right way to do it?

Charlie
  • 22,886
  • 11
  • 59
  • 90
WouldBeNerd
  • 629
  • 11
  • 29

1 Answers1

2

There are at least 4 (!) principal ways to clone an array:

  • loop
  • constructor
  • slice / splice
  • concat

Please see this answer

Community
  • 1
  • 1
Charlie
  • 22,886
  • 11
  • 59
  • 90