Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda