When I initialize an array, I found a weird situation.
JS code:
var arr = [1, 2, 3, 4, 5];
for(var i=0, arr2=[]; i < 5; arr2[i] = arr[i++])
console.log(arr2, i);
Output:
[] 0
[1] 1
[1, 2] 2
[1, 2, 3] 3
[1, 2, 3, 4] 4
arr2
initializes to [1, 2, 3, 4, 5] this is what i want
Look at this piece of code :
for(var i=0, arr2=[]; i < 5; arr2[i++] = arr[i])
console.log(arr2, i);
This code initializes arr2
to [2, 3, 4, 5, undefined]
i thought ++
operator operates before next line and both code will be same.
But, it operates differently. Why does this happen?
add explanation
I thought both for loop operates like this
var i = 0;
var arr2 = [];
check i < 5
console.log(arr2, i);
arr2[i] = arr[i];
i = i + 1;
check i < 5
....skip
is this thought wrong?
what is differance between
'arr2[i] = arr[i++];' and
'arr2[i++] = arr[i];'