Reputation: 4902
I found an issue/bad behavior Array.push(). I'm not sure if I'm doing something wrong or if .push() method is incorrect.
I will present a small example of what I'm dealing with
var x = [];
function test()
{
var y = x;
for(var i = 1; i<10; i++)
{
y.push(i);
}
alert("x = " + x);
}
alert("x = " + x);
test();
//result:
//1'st alert: x =
//2'rd alert: x = 1,2,3,4,5,6,7,8,9
So my example is incomparable small with the real problem what I had in my project, I did fix it: adding methods parameters (x sent as parameter not shared with global scope) or objects cloning where was the case.
Questions::
x
when the push is performed on y
initialized with x
?Maybe my question is dumb, but I cannot find documented explanation.
Thank you.
Upvotes: 1
Views: 1233
Reputation: 1074
var x = [];
an Array object is created, a variable x
is created, and pointer to the Array object is put in x
.
var y = x;
A variable y
is created, and pointer to array is copied from x
to y
.
Now both variables point to the same Array object.
It doesn't matter now what variable you will use to push, the same Array object will be pushed.
If you need to have different array, you need to copy the array, not the pointer. That is, create new Array object and push it with the values from other Array object. (Or use some copy function if available)
Upvotes: 0
Reputation: 338158
Why push change
x
when the push is performed ony
initialized withx
?
Because y
is not "initialized with x
", it is x
. In Javascript all variables contain references (with the exception of primitive values, like strings or numbers).
x
is a name for an array. Stating y = x;
merely creates another name for the same array.
This example happens cross browsers, and I wondered if node.js do the same well surprise it does,
Of course. It's in the spec that way.
now the question: I'm using wrong .push() method?
Yes. (Well, no, you're using it right, you just expected the wrong thing.)
And what is the correct approach to initialize objects from existing ones.
If you want to clone an object, there are different methods of going about it, depending on whether you want a shallow or a deep clone. This information can be looked up easily, I won't provide yet another implementation.
Related search: https://stackoverflow.com/search?q=javascript+clone+object
Upvotes: 1
Reputation: 24276
This is happening because you call the function after doing the second alert. The empty results is from the alert outside the function and the second one is the alert inside the function. This should work properly:
var x = [];
function test()
{
var y = x;
for(var i = 1; i<10; i++)
{
y.push(i);
}
alert("x = " + x);
}
test();
alert("x = " + x);
Upvotes: 0