Syntax
sort(compareFunction)
Description
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.
If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:
So, the compare function has the following form:
function compare(a, b) {
if (a is less than b by some ordering criterion)
return -1
if (a is greater than b by the ordering criterion)
return 1
// a must be equal to b
return 0
}
To compare numbers instead of strings, the compare function can simply subtract b from a:
function compareNumbers(a, b) {
return a - b
}
示例:
上例运行结果:
stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback
numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200
numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700
mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700