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

1 に答える 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.

于 2013-02-17T19:11:58.193 に答える