Iteration over numeric Array in javascript returns strings

Why

for (i in [1, 2, 3]) console.log(typeof(i), i);

gives this:

[Log] string 0
[Log] string 1
[Log] string 2

I've expected numbers.

@ Safari 7.0 (9537.71), Mac OS X 10.9

Answers:

Answer

That is because an Array in Javascript is a special Object with property keys (which are strings) used as indices. you are iterating that Array like an Object and because of that i is seen as a property key, a string.

To iterate in the right way an Array you have to use the following:

for( var i=0; i < [1,2,3].length; i++){ ... }
Answer

Try instead:

var arr = [1, 2, 3];
for (var i in arr)
    console.log(typeof arr[i], arr[i]);

You're getting strings rather than numbers because for..in loops iterate keys/properties (in this case, the Array's indices) rather than values.

To get the value of each key, i, you'll have to use a property accessor, arr[i].


Though, why strings at all rather than the original number indices is because, with current standards, all properties are strings.

console.log(Object.keys( ['foo', 'bar', 'baz'] )); // ["0", "1", "2"]

Any value can actually be used with property accessors, but it'll be converted ToString() before it's actually used as a key/property.

6) Let propertyNameString be ToString(propertyNameValue).

Maps and Symbols are currently planned to be the exceptions to that.


Also, you may find "Why is using “for…in” with array iteration such a bad idea?" of interest and at least consider using a simple for loop instead:

var arr = [1, 2, 3];
for (var i = 0, l = arr.length; i < l; i++)
    console.log(typeof arr[i], arr[i]);

Though, for future reference, the upcoming ECMAScript 6 standard has added for..of loops, which should iterate as you were expecting.

for (var i of [1, 2, 3])
    console.log(typeof i, i); // number, 1, 2, 3

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.