JavaScript IE 9: Custom sort function
In IE 9,开发者_开发问答 if I type this in the console:
[1, 4, 2, 3].sort(function (a, b) { return a < b; });
The resulting array is: [1, 4, 2, 3]
.
If I do this in FF/Chrome, I get it, reverse-sorted: [4, 3, 2, 1]
.
How come this doesn't work in IE?
EDIT: Is there a function out there that abstracts these browser differences? In other words, is there a function I can pass function(a, b) { return a < b; } in and get the same result in all browsers? Any open-source stuff?
Maybe because the function is supposed to return -1
if a
is smaller, 0
if they are equal, and 1
if a
is larger (or vice versa if you want reverse order). Edit: In fact, it must be zero, a positive or negative number (as @pimvdb pointed out, and that's what I make use of in the example below). Your function will never return -1
though and that might create problems.
Consider 1
and 3
. Your function returns 1
for 1 < 3
, which is ok, but returns 0
for 3 < 1
. In one case the number are different, in the other you are saying that they are equal.
That FF/Chrome sort it in reverse order might be due to the sorting algorithm they are using.
Try:
[1, 4, 2, 3].sort(function (a, b) { return b - a; });
Update: To substantiate this, we can have a look at the specification, Section 15.4.4.11 Array.prototype.sort(comparefn), where the properties are given which have to be fulfilled by a comparison function:
A function comparefn is a consistent comparison function for a set of values
S
if all of the requirements below are met for all values a, b, and c (possibly the same value) in the setS
: The notation a <CF b means comparefn(a,b) < 0; a =CF b means comparefn(a,b) = 0 (of either sign); and a >CF b means comparefn(a,b) > 0.
- Calling comparefn(a,b) always returns the same value v when given a specific pair of values a and b as its two arguments. Furthermore, Type(v) is Number, and v is not NaN. Note that this implies that exactly one of a <CF b, a =CF b, and a >CF b will be true for a given pair of a and b.
- Calling comparefn(a,b) does not modify the this object.
- a =CF a (reflexivity)
- If a =CF b, then b =CF a (symmetry)
- If a =CF b and b =CF c, then a =CF c (transitivity of =CF)
- If a <CF b and b <CF c, then a <CF c (transitivity of <CF)
- If a >CF b and b >CF c, then a >CF c (transitivity of >CF)
NOTE The above conditions are necessary and sufficient to ensure that comparefn divides the set S into equivalence classes and that these equivalence classes are totally ordered.
精彩评论