javascript - for.in 的迭代顺序——不是通过插入(还有吗?)

标签 javascript sorting for-in-loop

根据我的研究,for..in 循环中键的顺序应该是不确定的/不可靠的——但是,如果不受干扰,应该是插入顺序——但它不是:

我从数据库中获取这个数据对象,按名称排序:

var travel = {  
    '2': { name: 'bus',  price: 10 },  
    '3': { name: 'foot', price: 0 },  
    '1': { name: 'taxi', price: 100 }  
}  
for (way in travel) console.log( travel[way].name ) // => taxi, bus, foot  

按键按数字排序(在所有 Chrome、Firefox 和 Edge 中)。为什么?

而且(因为我错了)我如何遍历按 .name 排序的它们?

最佳答案

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

未定义,是的。

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

不,你第一次是对的:它是未定义的。即使在确实为某些其他操作提供属性顺序的 ES2015(又名“ES6”)及更高版本中,也不需要较旧的操作 for-inObject.keys遵循为新的定义的顺序。

在那些其他操作(Object.getOwnPropertyNamesJSON.serialize、...)中,顺序 ( defined here) 不是纯粹的插入顺序:Properties根据规范的定义*,其名称是数组索引,按数字顺序排在第一位。大多数主要的 JavaScript 引擎都更新了它们对 for-in 的处理以匹配它们对这些新操作的处理(许多已经对数组索引进行了不同的处理,但是它们在是否将它们放在非 - array-indexes 或之后),但同样,它是未定义的,您不应该依赖它。

如果你想要纯插入顺序,ES2015 的 Map 提供了,不管键的值是什么。对象没有。

这是一个使用 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 “数组索引”的是:

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.

关于javascript - for.in 的迭代顺序——不是通过插入(还有吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42595638/

相关文章:

javascript - 如何使用 Canvas 更改上下文弧的不透明度?

javascript - knockout - 它是如何工作的?

java - 为什么同一个Comparator在单元测试中的行为与作为Web应用程序运行时的行为不同?

linux - 按列和一般编号对床文件进行排序

javascript - 将 Node.js 应用程序部署到 heroku 时出现 Async.times 错误(重复循环)

ios - For-in 循环需要 'JSON?' 才能符合 'Sequence' ;你的意思是打开可选的吗?

javascript - 与 jQuery 相比,新的 oData javascript 库(来自 MSFT)

javascript - 出现 "undefined is not a function"错误

javascript - 将数字的javascript数组拆分为范围

javascript - "var x = "theBomb"in megalomaniac; "有什么作用?