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

112
Visualizações
loop over array of numbers using for...in shows unexpected results

I have a js script.

I want to alert each number in an array.

But it always shows from 0 instead of the actual number.

var indexes = [1,2]
arrayOfDigits = indexes.map(Number);
var i = 0;
for (i in arrayOfDigits)
 {
                alert(i);
 }

It alerts 0 then 1. But I want 1 then 2

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Quite a number of issues with your code, let's go through them:

  1. for...in is meant to be used to iterate over own, enumerable properties of objects, not for iterating over array members. You need for...of for this instead.

  2. Don't use var any more unless you explicitly know and need its special scoping behaviour. Use const instead, or let in case you need to assign to it more than once.

  3. Your code has an undeclared variable which automatically makes it a global variable. It is common consensus to not pollute the global namespace. Always declare any variables before use.

  4. Don't initialize or even declare the loop variable of a for...of loop outside of the loop. This is done right in the for (const digit of arrayOfDigits) construct itself.

  5. Don't use alert for debugging; use console.log instead.

Here's the working, corrected code:

const indexes = [1, 2]
const arrayOfDigits = indexes.map(Number);

for (const digit of arrayOfDigits) {
  console.log(digit);
}

about 4 years ago · Juan Pablo Isaza Relatório

0

The for-in loop loops over all the property of an object (including those from its prototype chain). All you want is to iterate over it. For that you can use a for-of loop (which loops over elements), or you could use Array#forEach which does just that but can help you have access to other stuff like the index:

indexes.forEach(number => {
    alert(number);
 });
about 4 years ago · Juan Pablo Isaza Relatório

0

If you are keen to have output as 1 and 2 use this instaed,

var indexes = [1,2]
    arrayOfDigits = indexes.map(Number);
    for (var i = 0;i<arrayOfDigits.length;i++)
     {
                    alert(arrayOfDigits[i]);
     }

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