How can JavaScript arrays have non-numeric keys?

后端 未结 2 1520
醉梦人生
醉梦人生 2020-12-19 20:54

What I have learned is an array is a type of object. Objects are a collection of properties with key/value pairs. I always thought arrays are a collection of items that are

2条回答
  •  半阙折子戏
    2020-12-19 21:19

    With a for..of loop, the object's Symbol.iterator property is called. In the case of an array, this is equivalent to the array's .values() method, which contains the values for each index in the array. Non-numeric properties are not included - arrays generally don't have arbitrary non-numeric properties, and code that does assign arbitrary non-numeric properties to an array is likely in need of refactoring.

    A for..in loop iterates over all enumerable properties on an object, including those inherited from the prototype. Thus, for..of on an array will exclude non-numeric properties on an array that a for..in loop will include.

    Arrays, being objects, can have arbitrary properties assigned to them, for the most part, just like properties can be assigned to ordinary functions - it's just not a very good idea.

提交回复
热议问题