1

Not sure if what I want is possible, but

This works:

pointer = arr1 = ['a','b','c'];
arr1.splice(0, 1);
console.log(pointer); // ['b','c']

What I would like, but does not work:

pointer = arr1 = ['a','b','c'];
arr1 = ['e','f'];
console.log(pointer); // desired ['e','f']
console.log(pointer); // reality ['a','b','c']

Is there any way around this, other than constantly re-updating the pointer variable each time arr1 gets reassigned?

2
  • 1
    No, JavaScript doesn't have pointers. The only way would be if you put the Array in an Object, then updated the Object's Array. Then any reference to the Object would see the update. Commented Sep 10, 2013 at 17:57
  • That is brilliant! I will use an object and store the array inside, then save a reference to the object. That way reassignment of the property wont break the original reference. Please put this in an answer. Commented Sep 10, 2013 at 18:00

2 Answers 2

2

No, JavaScript doesn't have pointers. The only way would be if you put the Array in an Object, then updated the Object's Array. Then any reference to the Object would see the update.

var pointer = arr1 = {array:['a','b','c']};
arr1.array = ['e','f'];

console.log(arr2.array);    // ['e','f']
console.log(pointer.array); // ['e','f']
Sign up to request clarification or add additional context in comments.

Comments

1

Javascript do not have pointers.

Suggestion given by @user2736012 in comments is a good idea ie to put Array in an Object, then updated the Object's Array. Then any reference to the Object would see the update.

Comments

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.