元素顺序在“for(... in ...)”中循环 [英] Elements order in a "for (… in …)" loop

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

问题描述

JavaScript中的for ... in循环是否按照声明的顺序循环访问hashtables /元素?有没有一个浏览器,它不会按顺序?

我希望使用的对象将被声明一次,永远不会被修改。



假设我有:

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

我进一步使用它们:

<$ (myObject中的var项目)alert(item +:+ myObject [item]); p $ p>

我可以期待'A:'Hello''总是出现在'B:'World''在最合适的浏览器?

解决方案

引用John Resig


目前所有主流浏览器都会遍历对象的属性他们被定义的
的订单。 Chrome也会这样做,除了一些情况。 [...]
此行为由ECMAScript规范显式地左定义。
在ECMA-262第12.6.4节中:

lockquote

枚举属性...的机制取决于实现。 / p>

但是,规范与实现完全不同。 ECMAScript的所有现代实现
按照它们被定义的顺序遍历对象属性。
正因为如此,Chrome团队认为这是一个错误,并将解决它。


所有浏览器都尊重定义除除Chrome 和Opera外,每个非 - 数字属性名称。在这两个浏览器中,这些属性在第一个非数值属性之前被拉入(这与他们如何实现数组有关)。这个命令与 Object.keys 相同。



这个例子应该清楚发生了什么: / b>

  var obj = {
first:first,
2:2 ,
34:34,
1:1,
second:second
};
for(var i in obj){console.log(i); };
//列出的订单:
//1
//2
//34
//first
/ /second

这个技术的重要性并不比这个随时可能改变的事实重要。不要依赖这种方式。
$ b $ p

简而言之:如果订单对您很重要,请使用数组


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.

Suppose I have:

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

And I further use them in:

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

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

解决方案

Quoting John Resig:

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.

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.

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.

In short: Use an array if order is important to you.

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

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