Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
shift() method is not running correctly, it only shift for 2-3 times and then it wouldn't shift

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 ]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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();
}
about 4 years ago · Juan Pablo Isaza Report

0

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
}
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!