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

110
Views
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 answers
Answer question

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 Report

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 Report

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