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?
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!
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With