IE9 javascript排序顺序...为什么? [英] IE9 javascript sort order ... why?

查看:107
本文介绍了IE9 javascript排序顺序...为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当比较函数返回0时,我注意到IE9排序顺序正在更改元素顺序.

I noticed IE9 sort order is changing elements order when comparison function returns 0.

请参阅:

var myarray=[
    {id:1,val:0},
    {id:2,val:0},
    {id:3,val:7},
    {id:4,val:41}
];
myarray.sort(function(a,b){return a.val - b.val});

for(var i in myarray)
{
    console.log(myarray[i].id);
}

Chrome,Firefox,Opera和Safari的当前稳定版本获得以下输出:1 2 3 4.

Current stable versions of Chrome, Firefox, Opera and Safari got the following output: 1 2 3 4.

对于IE7和IE8,输出相同.

Same output for IE7 and IE8.

IE9的输出是:2 1 3 4

为什么?正常吗?

推荐答案

来自 MDC (重点是我的):

如果compareFunction(a,b)返回0,则使a和b相对不变,但对所有不同元素进行排序. [注意:ECMAscript标准不能保证此行为] ,因此,并非所有浏览器(例如,至少可追溯到2003年的Mozilla版本)都遵守这一要求.

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. [Note: the ECMAscript standard does not guarantee this behaviour], and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

以我的经验,只有Chrome/Firefox可以正确使用此功能. Opera 11对我的行为还没有明确定义.

In my experience, only Chrome/Firefox get this right. Opera 11's behavior for me is .. not well defined.

例如,使用sort将所有零移动到数组顶部:

E.g., using sort to move all zeroes to the top of the array:

[1, 0, 3, 0, 5, 0, 2].sort(function (a, b) { return b === 0 && 1 || 0;});

  • 铬10:[0,0,0,1,3,5,2]
  • Firefox 4:[0、0、0、1、3、5、2]
  • 歌剧11:[0、0、0、2、1、5、3]<-不维持非零的顺序
  • 这篇关于IE9 javascript排序顺序...为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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