0

I am wanting to create a private array within an object. The problem is that I am copying obj.arr with arrCopy but it seems to only reference obj.arr. This is causing issues when I splice it as it is affecting obj.arr which on any further runs of the code will be shorter.

here is a codepen with an example of the code to play with.

here is the javascript of concern

var obj = {
  min: 3,
  max: 9,
  // I want the array to be private and never to change.
  arr : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
  inside: function(){
    // I want this variable to copy the arrays values into a new array that can be modified with splice()
    var arrCopy = this.arr;
      console.log('obj.arr: ' + this.arr);
      console.log('arrCopy: ' + arrCopy);
    // I want to be able to splice arrCopy without affecting obj.arr so next time the function is run it gets the value of obj.arr again
    var arrSplit = arrCopy.splice(arrCopy.indexOf(this.min), (arrCopy.indexOf(this.max) - arrCopy.indexOf(this.min) + 1));
    console.log('arrSplit: ' + arrSplit);
    console.log('obj.arr: ' + this.arr);
  }
}

//to run un-comment the next line
//obj.inside();

thanks for any help,

Regards,

Andrew

synthet1c
  • 6,152
  • 2
  • 24
  • 39
  • possible duplicate of [Is there a method to clone an array in jQuery?](http://stackoverflow.com/questions/3775480/is-there-a-method-to-clone-an-array-in-jquery) – Denis Oct 05 '13 at 07:09
  • possible duplicate of [Copying array by value in javascript](http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript) – Barmar Oct 05 '13 at 07:10

1 Answers1

3

When you assign objects or arrays in Javascript, it just copies a reference to the original array or object, it doesn't copy the contents. To make a copy of an array, use:

var arrCopy = this.arr.slice(0);
Barmar
  • 741,623
  • 53
  • 500
  • 612