Question

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

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top