It seems like JavaScript somehow tries to optimize code, so if we want to fill a multidimensional array (largeArr
) with changing values of one-dimensional array (smallArr
) within a loop and use this code:
largeArr = []
smallArr = []
for (i=0; i<2; i++)
{
smallArr[0]=i
smallArr[1]=2*i
largeArr[i]=smallArr
}
we get an unexpected result: largeArr=[[1,2],[1,2]]
(must be [[0,0],[1,2]]
). So, Javascript calculates smallArr
values in the first place, and only then fills largeArr
.
To get the right result we must declare smallArr
in the loop:
largeArr = []
for (i=0; i<2; i++)
{
smallArr = []
smallArr[0]=i
smallArr[1]=2*i
largeArr[i]=smallArr
}
and then it works as expected (largeArr=[[0,0],[1,2]]
).
Why does it behave this way?