头图

Array.prototype.sort()

The sort() method is used to sort the elements of an array. If no parameters are used when calling this method, the elements in the array will be sorted in alphabetical order (Ascall code). To be more precise, it is sorted in the order of character codes. To achieve this, first convert all the elements of the array into strings (if necessary) for comparison. If you want to sort in ascending or descending order, provide a comparison function.

  • The sort order can be letters or numbers, and in ascending or descending order.
  • The default sort order is ascending alphabetically.

Syntax :
array.sort(sortfunction)

parameterdescribe
sortfunctionOptional. Specifies the sort order. Must be a function.
  • Conditions for ascending and descending order
当 a>b 时,
a - b > 0  ,排序结果 ===> b,a (升序)
b - a < 0  ,排序结果 ===> a,b (降序)

当 b>a 时,
a - b < 0  ,排序结果 ===> a,b (升序)
b - a > 0  ,排序结果 ===> b,a (降序)

当 a=b 时,
a - b = b - a =0 , 排序结果 ===> 保持不变

ascending order

// 升序
var points = [40,100,1,5,25,10];
let res = points.sort(function(a,b){
    return a-b    //升序
});

console.log(res);  [ 1, 5, 10, 25, 40, 100 ]

descending order

// 降序
var points = [40,100,1,5,25,10];
let result = points.sort(function(a,b){
    return b - a
});

console.log(result);  //[ 100, 40, 25, 10, 5, 1 ]
 

in ascending alphabetical order

//按字母升序 
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits)  //[ 'Apple', 'Banana', 'Mango', 'Orange' ]

云绮棠兮
48 声望10 粉丝

当野心追赶不上才华,便静下心来努力