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...

Ziarno
  • 7,366
  • 5
  • 34
  • 40
  • One of those will probably help you: http://stackoverflow.com/search?q=[javascript]+copy+array. – Felix Kling Feb 17 '13 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);`. – loganfsmyth Feb 17 '13 at 19:13
  • possible duplicate of [Copying array by value in javascript](http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript) --- with nearly the same example. – Felix Kling Feb 17 '13 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? – Ziarno Feb 17 '13 at 19:55

1 Answers1

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.

MaxArt
  • 22,200
  • 10
  • 82
  • 81