Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the index of an array a string in the below code? [duplicate]

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 78];
for(var index in arrayOfNumbers){
   console.log(index+1);
}

The output for this sample code is.
01
11
21
31
41
51
61

Why are these indexes of an array treated as a string in JavaScript?

like image 962
rohitwtbs Avatar asked Oct 17 '22 21:10

rohitwtbs


1 Answers

From MDN for...in

Note: for...in should not be used to iterate over an Array where the index order is important.

... The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.

When using for...in, the key is always a string and all it does is string concatenation.

You have an array, so better use Array.foreach() like so:

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 78];
arrayOfNumbers.forEach(function(item, index){
     console.log(index + 1); // Here the index is a number!
});
like image 157
caramba Avatar answered Nov 15 '22 04:11

caramba