0

So, this is working not as I'd expect it to:

var x = [1,2,3];
var y = x;
y.push(4);
console.log(x);

I thought it'd log [1,2,3] but it logs [1,2,3,4]! What I need is to have a function that only adds a value to y, not x - I want to be able to mess around with the [1,2,3] array, but also be able to "come back to it" and cancel the changes made. I hope that makes enough sense...

4
  • One of those will probably help you: stackoverflow.com/search?q=[javascript]+copy+array. Commented Feb 17, 2013 at 19:12
  • 2
    Arrays are reference types, just like objects. It's the same as doing var x = {}; var y = x; y.key = 'val'; console.log(x);. Commented Feb 17, 2013 at 19:13
  • possible duplicate of Copying array by value in javascript --- with nearly the same example. Commented Feb 17, 2013 at 19:14
  • You're right, it's a duplicate, sorry guys I couldn't find it - should I delete this one, or let it be? Commented Feb 17, 2013 at 19:55

1 Answer 1

3
var x = [1,2,3];
var y = x.slice();
y.push(4);
console.log(x);  // Outputs 1,2,3

Using slice is the simplest way to get a copy of an array.

Keep in mind that in Javascript x and y are references to arrays. In this, Javascript behaves differently than, for example, PHP.

So when you do y.push(4) you're pushing an element into the same array referenced by x.

Sign up to request clarification or add additional context in comments.

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.