Iteration over numeric Array in javascript returns strings

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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

回答1:

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++){ ... } 


回答2:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!