This piece of code will print [1,2,3,4,5,6,7,8,9,10]
on the console it means in every iteration arr.length change and this is reflected in the loop body also.
let arr = [1, 2, 3];
for (e of arr) {
arr.push(arr[arr.length - 1] 1);
if (arr.length >= 10) break;
}
console.log(arr)
But here, The output will be [4,5,6]
and that mean the shift() function is not considering the expansion of the array.
let arr = [1, 2, 3];
for (e of arr) {
arr.push(arr[arr.length - 1] 1);
if (arr[arr.length - 1] >= 10) break;
arr.shift();
}
console.log(arr)
My question is why? I expected [8,9,10]
output from second code
CodePudding user response:
The reason is that you have add element at first,then you invoke shift()
to remove the element,so the array size will not change and it will only iterate once
let arr = [1, 2, 3];
for (e of arr) {
arr.push(arr[arr.length - 1] 1); // add element
if (arr[arr.length - 1] >= 10) break;
arr.shift(); // remove element
}
console.log(arr)
In order to get your expected result,we need to make sure it can iterate more than once until got the expected result. So we can change for
to while
let arr = [1, 2, 3];
while(arr.at(-1) < 10) {
arr.push(arr.at(-1) 1);
arr.shift();
}
console.log(arr)
CodePudding user response:
The second for ...of
loop is working correctly:
let arr = [1, 2, 3];
for (e of arr) {
arr.push(arr[arr.length - 1] 1); // 4, 5, 6
if (arr[arr.length - 1] >= 10) break; // false, false, false
arr.shift(); // 1, 2, 3
}
console.log(arr); // [ 4, 5, 6 ]
Because you are removing the first element of the array in each loop with shift()
, your array never exceeds 3 elements at the beginning of the loop, so it will only loop 3 times.
hope this helps.