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::
- Why push change
x
when the push is performed ony
initialized withx
? - This example happens cross browsers, and I wondered if node.js do the same well surprise it does, now the question: I'm using wrong .push() method? And what is the correct approach to initialize objects from existing ones.
Maybe my question is dumb, but I cannot find documented explanation.
Thank you.