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
Quite a number of issues with your code, let's go through them:
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.
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.
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.
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.
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);
}
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);
});
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]);
}