Iteration order of for.in – not by insertion (any more?)

故事扮演 提交于 2019-12-05 06:12:35

According to my research, the order of keys in a for..in loop should be undefined/unreliable

Undefined, yes.

  • but, if left undisturbed, should be in insertion order

No, you were right the first time: It's undefined. Even in ES2015 (aka "ES6") and above, which do provide property order for some other operations, the older operations for-in and Object.keys are not required to follow the order defined for the new ones.

In those other operations (Object.getOwnPropertyNames, JSON.serialize, ...), the order (defined here) isn't purely insertion order: Properties whose names are array indexes according to the spec's definition* come first, in numeric order. Most major JavaScript engines have updated their handling of for-in to match their handling of these new operations (many already did treat array indexes differently, but they varied in terms of whether they put those before the non-array-indexes or after), but again, it's undefined, and you shouldn't rely on it.

If you want pure insertion order, ES2015's Map provides that, regardless of the value of the key. Objects don't.

Here's an example using Map:

const map = new Map([
  ['2', { name: 'bus',  price: 10 }],
  ['3', { name: 'foot', price: 0 }],
  ['1', { name: 'taxi', price: 100 }]
]);
for (const entry of map.values()) { // bus, foot, taxi
  console.log(entry.name);
}

* The spec's definition of an "array index" is:

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253-1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232-1.

In practice, javascript object iterates by keys in insertion order except when keys are numeric. This is probably caused be the need to make array iteration (arrays are objects too) ordered by key.

So, your choices are - respect the standard and use ES6 Map or arrays of objects to guarantee iteration order - make your keys always non-numeric and hope for the best

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