Home > front end >  shift() method is not running correctly, it only shift for 2-3 times and then it wouldn't shift
shift() method is not running correctly, it only shift for 2-3 times and then it wouldn't shift

Time:10-05

Here is my code please give some solutions.

Input:-

var b = [167,244,377,56,235,269,23];

for(var temp=0;temp<b.length;temp  ){

    console.log(b)
    b.shift();
}

output:-

[ 167, 244, 377,56, 235, 269,23]
[ 244, 377, 56, 235, 269, 23 ]
[ 377, 56, 235, 269, 23 ]
[ 56, 235, 269, 23 ]

CodePudding user response:

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();
}

CodePudding user response:

I order to continue looping until b has no elements, remove the temp increment:

var b = [167, 244, 377, 56, 235, 269, 23];
for (var temp = 0; temp < b.length;) {
  console.log(b)
  b.shift();
}

CodePudding user response:

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
}
  • Related