I was toying with for … loops, bumped into something weird
function turnaround (arr) {
var nwarr = [];
// console.log(arr.length);
for (var i = 0; i < arr.length; i++){
// console.log(i);
var out = arr.pop();
nwarr.push(out);
}
return nwarr;
}
turnaround ([1,2,3,4,5,6,7,8,9]); // Array(5) [ 9, 8, 7, 6, 5 ]
Huh? The output? Array only 5?
However:
changed it into ’ for (var i = 0; i < 9; i++) and then the array was completed: // Array(9) [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
So:
With ‘i < arr.length’ my loop goes only 5 x, output Array(5) [ 9, 8, 7, 6, 5 ]
However ‘arr.length = 9’, as checked and confirmed by ‘console.log(arr.length);’
I changed ‘i < arr.length’ into ‘i < 9’, and the loop completes neatly after 9 x.
I changed back into ‘i < arr.length’ and again the loop stops after 5 x.
Anyone understanding this?