JavaScript自动排序在Firefox和其他浏览器 [英] Javascript auto-sort in firefox vs Other browsers

查看:138
本文介绍了JavaScript自动排序在Firefox和其他浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在Firefox中发现了这个奇怪的行为:



这段代码自动排序属性:

  var an_obj = {4:d,1:a,2:c}; 
alert(Object.keys(an_obj)); //会提醒1,2,4

虽然这不是:

  var value2 = {1003:1,1001:2,1000:3}; 
alert(Object.keys(value2)); //将提示1003,1001,1000

任何大于1000的数字在Firefox中都会有不同的行为,而其他浏览器(Chrome,IE11)的行为与预期的大于1000的自动排序数字相同。



我相信这是FireFox中的一个错误,我错了吗?



更新1

这使得在FireFox的相同实现中,这个命令不可预知。我可以理解值根本不排序,或根据一个标准进行排序,但不能在任意数字之后表现不可预测的。 解决方案

这不是一个错误。对象不保证在它们的属性中有任何顺序,并且在某些情况下,不应该依赖 Object.keys 来进行任何排序。



ECMAScript 5标准的§15.2.3.14中有关<$ c

$ b


如果一个实现定义了for-in的枚举的特定顺序语句,在这个算法的第5步中必须使用相同的枚举顺序。

这意味着任何对 for-in 语句和 Object.keys 完全依赖于实现。


Recently I found this odd behavior in Firefox:

This code auto-sort the properties:

var an_obj = { "4": "d", "1": "a", "2": "c"};
alert(Object.keys(an_obj)); // will alert "1, 2, 4"

While this one is not:

var value2 = {"1003":1, "1001":2, "1000":3};
alert(Object.keys(value2));// will alert "1003, 1001, 1000"

Any number greater than 1000 will have a different behavior in Firefox while other browsers(Chrome, IE11) will behave as expected auto-sorting numbers greater than 1000.

I believe this is a bug in FireFox, am I wrong?

Update 1

This makes the order "unpredictable" inside the same implementation of FireFox. I could understand values not being sort at all or sort accordingly one criteria but not behaving "unpredictably" after an "arbitrary" number.

解决方案

This is not a bug. Objects do not guarantee any order in their properties and any ordering with Object.keys in some cases should not be depended on.

It is stated in §15.2.3.14 ECMAScript 5 standard about Object.keys that

If an implementation defines a specific order of enumeration for the for-in statement, that same enumeration order must be used in step 5 of this algorithm.

which implies that any ordering for the for-in statement and Object.keys is entirely implementation-dependent.

这篇关于JavaScript自动排序在Firefox和其他浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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