How can JavaScript arrays have non-numeric keys?

后端 未结 2 1495
醉梦人生
醉梦人生 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 20:56

    Arrays are a type of objects in javascript. When you do something like arr.skin = 'white';, you're basically setting a variable to the array's object property collection. That's why you can access it with in for...of, which iterates over the enumerable properties of the object.

    However, since this new property is not part of the array's list of elements, it cannot be accessed through for...in

    Taken from MDN web docs for Arrays:

    Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

提交回复
热议问题