IE9 javascript sort order … why?

℡╲_俬逩灬. 提交于 2019-12-11 12:45:26

问题


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

See:

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);
}

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

Same output for IE7 and IE8.

IE9 output is: 2 1 3 4

Why? Is that normal?


回答1:


From MDC (emphasis mine):

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.

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

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;});
  • Chromium 10: [0, 0, 0, 1, 3, 5, 2]
  • Firefox 4: [0, 0, 0, 1, 3, 5, 2]
  • Opera 11: [0, 0, 0, 2, 1, 5, 3] <- does not maintain order of non-zeroes



回答2:


Don't use for...in on an array if you're trying to iterate over the numeric properties, for two reasons:

  • You will also get methods and properties added to Array.prototype showing up;
  • The iteration order is defined in the ECMAScript spec as being implementation-dependent, meaning it could in theory be anything.

Both points also apply to Objects. Chrome in fact does not conform to the most common browser behaviour, leading to heated debate in a Chrome bug report.




回答3:


Based on your sort function, both of those elements are equal and it shouldn't matter which order they appear in. It is up to the browser to either leave the order as it is or switch the order as it sees appropriate...neither is a guarantee.

If the two aren't equal, then your sort function is incorrect and should take the other items into account as well.



来源:https://stackoverflow.com/questions/4782893/ie9-javascript-sort-order-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!