Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda