Array之sort()

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:

  • If compareFunction(a, b) is less than 0, sort b to a lower index than a.

  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

  • If compareFunction(a, b) is greater than 0, sort b to a higher index than a.

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

 

你可能感兴趣的:(javascript,HTML)