JavaScript IE 9: Custom sort function

前提是你 提交于 2019-12-11 10:26:46

问题


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?


回答1:


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 set S: The notation a <CFb means comparefn(a,b) < 0; a =CFb means comparefn(a,b) = 0 (of either sign); and a >CFb 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 <CFb, a =CFb, and a >CFb will be true for a given pair of a and b.
  • Calling comparefn(a,b) does not modify the this object.
  • a =CFa (reflexivity)
  • If a =CFb, then b =CFa (symmetry)
  • If a =CFb and b =CFc, then a =CFc (transitivity of =CF)
  • If a <CFb and b <CFc, then a <CFc (transitivity of <CF)
  • If a >CFb and b >CFc, then a >CFc (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.



来源:https://stackoverflow.com/questions/7501515/javascript-ie-9-custom-sort-function

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