Does JavaScript array.forEach traverse elements in ascending order

前端 未结 3 442
陌清茗
陌清茗 2020-12-29 19:48

In JavaScript I can have an array with holes:

a = [];
a[0] = 100;
a[5] = 200;
a[3] = 300;

a.forEach(function(x) {alert(x);});

I could not

3条回答
  •  旧时难觅i
    2020-12-29 20:19

    The specification says forEach will visit the array elements in numeric order. It doesn't visit elements that don't exist. See the link for details. So for your example array, it will visit element 0, then 3, then 5. The order in which you add them to the array has no effect on the order in which they're visited.

    I checked that "for .. in" loop traverses array indices in ascending order, while property names of an object are traversed in the same order they were added to object (at least it looks so).

    The order in which for-in visits object properties is not defined by the specification, not even in ES2015 (aka ES6), despite the fact that ES2015 defines an order for object properties — that order doesn't apply to for-in or Object.keys. (More about that in this answer.) If you want to visit properties in the order defined in ES2015, you can use Object.getOwnPropertyNames (for properties that aren't defined with Symbol names) or Reflect.ownKeys (for both Symbol and string property names [remember numeric property names are really strings]). Both of those do respect property order.

提交回复
热议问题