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)
parameter | describe |
---|---|
sortfunction | Optional. 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' ]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。