IE9 javascript sort order ... why?
I noticed IE9 sort order is changing elements order when comparison function returns 0
.
See:
v开发者_如何学Car 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?
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 Object
s. Chrome in fact does not conform to the most common browser behaviour, leading to heated debate in a Chrome bug report.
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
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.
精彩评论