Why for var in array returns a string index?

This question already has an answer here:

  • javascript for loop counter coming out as string 3 answers

  • My friend, behold the wonder and curse of prototypical inheritance. What you are iterating over with for..in isn't an array. You are iterating over an Array object. Take a look at the doc:

    Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

    Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the for...of loop) when iterating over arrays where the order of access is important.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

    So what you are dealing with are enumerable "integer names" of properties in an Array object, not numerical order.

    EDIT for v in array in JavaScript isn't equivalent to for v in list in python. It's equivalent to for k, v in dict.iteritems() but k is implicitly given to you as a string with integer name so to speak, ie "1", "2", "3", etc. I think it's counter-intuitive as well from an OO standpoint. How can a list/array be a dict-like object? But from a prototypical standpoint, so long as anything inherits from Object.prototype , it can be considered an Object with keys and properties.

    链接地址: http://www.djcxy.com/p/70104.html

    上一篇: 使用jQuery预加载图像

    下一篇: 为什么数组中的var返回一个字符串索引?