Javascript中的“for…in”循环是否按照声明的顺序遍历哈希表/元素?有没有浏览器是不按顺序执行的?
我希望使用的对象只声明一次,永远不会被修改。
假设我有:
var myObject = { A: "Hello", B: "World" };
我进一步将它们用于:
for (var item in myObject) alert(item + " : " + myObject[item]);
在大多数像样的浏览器中,“A:“Hello”总是出现在“B:“World”之前吗?
引用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.
所有浏览器都尊重定义顺序,除了Chrome和Opera,它们对每个非数字属性名都遵守定义顺序。在这两个浏览器中,属性被按顺序拉到第一个非数值属性之前(这与它们如何实现数组有关)。Object的顺序是一样的。还有钥匙。
这个例子应该清楚地说明发生了什么:
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"
这方面的技术细节并不重要,重要的是这一点随时都可能改变。不要指望事情会一直这样下去。
简而言之:如果顺序对你很重要,就使用数组。
订单不可信。Opera和Chrome都返回无序的属性列表。
<script type="text/javascript">
var username = {"14719":"A","648":"B","15185":"C"};
for (var i in username) {
window.alert(i + ' => ' + username[i]);
}
</script>
上面的代码显示了Opera中的B, A, C和Chrome中的C, A, B。