Elements order in a quot;for (… in …)quot; loop(元素按“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 ...)"顺序排列.环形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:元素按“for (... in ...)"顺序排列.环形
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01