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

2

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Wow that was quick!!, thanks for the answer Barmar it worked perfectly!
as a side note to this: if you end up putting objects/other arrays into the array and call slice it will use a reference of the objects/arrays in the new array
Thanks Patrick I will try to keep that in mind for the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.