Javascript 中的“for...in”循环是否按照声明的顺序循环遍历哈希表/元素?有没有不按顺序执行的浏览器?
我希望使用的对象将被声明一次并且永远不会被修改。
假设我有:
var myObject = { A: "Hello", B: "World" };
我进一步将它们用于:
for (var item in myObject) alert(item + " : " + myObject[item]);
在大多数不错的浏览器中,我可以期望“A:“Hello””总是出现在“B:“World””之前吗?
最佳答案
Currently all major browsers loop over the properties of an object in the order in which they were defined. Chrome does this as well, except for a couple cases. [...] This behavior is explicitly left undefined by the ECMAScript specification. In ECMA-262, section 12.6.4:
The mechanics of enumerating the properties ... is implementation dependent.
但是,规范与实现有很大不同。所有现代实现 ECMAScript 按照对象属性的定义顺序迭代它们。 因此,Chrome 团队认为这是一个错误,并将予以修复。
block 引用>所有浏览器都遵循定义顺序 with the exception of Chrome和 Opera 对每个非数字属性名称执行此操作。在这两个浏览器中,属性在第一个非数字属性之前按顺序拉取(这与它们实现数组的方式有关)。
Object.keys
的顺序相同。也是如此。这个例子应该清楚地说明发生了什么:
var obj = { "first":"first", "2":"2", "34":"34", "1":"1", "second":"second" }; for (var i in obj) { console.log(i); }; // Order listed: // "1" // "2" // "34" // "first" // "second"
其技术细节并不重要,重要的是它可能随时发生变化。不要指望事情会保持这种状态。
简而言之:如果顺序对您很重要,请使用数组。
关于javascript - "for (… in …)"循环中的元素顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309560/