How is the JavaScript sort function implemented?

Let's look at an example first.

var everything = [4,'Red', '$200', 'white', 7.4, 12, true, 0.3, false]; console.log(everything.sort(function(a, b) {return a - b;})); // [4, "Red", "$200", "white", false, 0.3, true, 7.4, 12] 

I think this is strange, even when I know Number("Red") , Number("$200") and Number("white") , all give NaN when compared.

Why 4 in the first result? I assume this has something to do with the implementation of Array.prototype.sort , so how can I see its implementation?

+7
javascript sorting
source share
1 answer

Specification

According to ECMAScript 5 - Section 15.4.4.11 ,

If comparefn is not undefined and is not a sequential comparison function for the elements of this array (see below), the sorting behavior is determined by the implementation ,

[...]

The comparefn function is a sequential comparison function for a set of values โ€‹โ€‹of S if all the requirements below are satisfied for all values โ€‹โ€‹of a, b, and c (possibly the same value) in the set S [...]

  • The call comparefn (a, b) always returns the same value of v when it is given a specific pair of values โ€‹โ€‹a and b as two arguments. In addition, Type (v) is Number, and v is not NaN . [...]

That is, if the return value of the comparison function is NaN, then the behavior of the call to sort is determined by "implementation".


On practice

Google Chrome and NodeJS (V8 Engine), as well as Opera (Futhark / Carakan) are returned:

 [4, "Red", "$200", "white", false, 0.3, true, 7.4, 12] 

Firefox (SpiderMonkey) returns:

 [false, 0.3, true, 4, "Red", "$200", "white", 7.4, 12] 

Internet Explorer returns:

 ["Red", "$200", false, 0.3, true, 4, "white", 7.4, 12] 
+6
source share

All Articles