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

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

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 Denunciar

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 Denunciar

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 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