Here is my code please give some solutions.
var b = [167,244,377,56,235,269,23];
for(var temp=0;temp<b.length;temp++){
console.log(b)
b.shift();
}
[ 167, 244, 377,56, 235, 269,23]
[ 244, 377, 56, 235, 269, 23 ]
[ 377, 56, 235, 269, 23 ]
[ 56, 235, 269, 23 ]
Condition in for-loop is checked everytime. And every time b.lenght is smaller and smaller.
You just need to save b.length somewhere and use its value.
var b = [167,244,377,56,235,269,23];
const length = b.length;
for(var temp=0;temp<length;temp++){
console.log(b)
b.shift();
}
When you shift you remove an items from the array. The array size shrinks. You are looping over the current array length, not the original array length.
i=0; b.length=7 --> 0 < 7 === true
i=1; b.length=6 --> 1 < 6 === true
i=2; b.length=5 --> 2 < 5 === true
i=3; b.length=4 --> 3 < 4 === true
i=4; b.length=3 --> 4 < 3 === false
So either you store the original length, you loop from length to zero, or use a while loop.
var b = [...]
var length = b.length;
for(var temp=0; temp<b.length; temp++){
//code
}
or
var b = [...]
for(var temp=b.length; temp>=0; temp--){
//code
}
or
while(b.length) {
//code
}
I order to continue looping until b has no elements, remove the temp++ final expression.
var b = [167, 244, 377, 56, 235, 269, 23];
for (var temp = 0; temp < b.length;) {
console.log(b);
b.shift();
}
Instead, you could move the shift method call to the final expression
var b = [167, 244, 377, 56, 235, 269, 23];
for (var temp = 0; temp < b.length; b.shift()) {
console.log(b);
}
Since we are removing elements from the array in the for loop, we should not increment temp at all. With that in mind, we can also convert the loop into a while loop.
var b = [167, 244, 377, 56, 235, 269, 23];
while (b.length > 0) {
console.log(b);
b.shift();
}