“for (... in ...)"中的元素顺序;环形 [英] Elements order in a "for (… in …)" loop

查看:32
本文介绍了“for (... in ...)"中的元素顺序;环形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript 中的for...in"循环是否按照声明的顺序遍历哈希表/元素?是否有浏览器不按顺序执行?
我希望使用的对象将被声明一次并且永远不会被修改.

Does the "for…in" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order?
The object I wish to use will be declared once and will never be modified.

假设我有:

var myObject = { A: "Hello", B: "World" };

我进一步将它们用于:

for (var item in myObject) alert(item + " : " + myObject[item]);

在大多数体面的浏览器中,我可以期望 'A : "Hello"' 总是出现在 'B : "World"' 之前吗?

Can I expect 'A : "Hello"' to always come before 'B : "World"' in most decent browsers?

推荐答案

引用 John Resig<​​/一个>:

Quoting John Resig:

目前所有主流浏览器都按照以下顺序循环遍历对象的属性他们被定义.除了少数情况外,Chrome 也会这样做.[...]ECMAScript 规范明确未定义此行为.在 ECMA-262 中,第 12.6.4 节:

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 团队认为这是一个错误,并将予以修复.

However, specification is quite different from implementation. All modern implementations of ECMAScript iterate through object properties in the order in which they were defined. Because of this the Chrome team has deemed this to be a bug and will be fixing it.

所有浏览器都遵守定义顺序Chrome 除外和 Opera 为每个非数字属性名称做.在这两个浏览器中,属性在第一个非数字属性之前按顺序拉取(这与它们如何实现数组有关).Object.keys 的顺序也相同.

All browsers respect definition order with the exception of Chrome and Opera which do for every non-numerical property name. In these two browsers the properties are pulled in-order ahead of the first non-numerical property (this is has to do with how they implement arrays). The order is the same for Object.keys as well.

这个例子应该清楚地说明发生了什么:

This example should make it clear what happens:

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"

这方面的技术细节不如随时可能改变的事实重要.不要依赖这样的事情.

The technicalities of this are less important than the fact that this may change at any time. Do not rely on things staying this way.

简而言之:如果顺序对您很重要,请使用数组.

这篇关于“for (... in ...)"中的元素顺序;环形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆