springboot
springboot

Reputation: 61

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

Upvotes: 0

Views: 65

Answers (3)

martin66
martin66

Reputation: 387

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);
 });

Upvotes: 0

connexo
connexo

Reputation: 56773

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);
}

Upvotes: 2

Manu Jo Varghese
Manu Jo Varghese

Reputation: 400

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]);
     }

Upvotes: 0

Related Questions