@TOC
排序顺序
使用sort在实际使用中主要是实现排序,分为升序和降序,官网的解释是
- If compareFunction(a, b) returns a value > than 0, sort b before a.
如果返回的值大于0 ,则 b在a前面
- If compareFunction(a, b) returns a value < than 0, sort a before b.
如果返回的值小于0,则a在b前面
- If compareFunction(a, b) returns 0, a and b are considered equal.
如果两个值相等,则不变
Note: The ECMAScript Standard, 10th edition (2019) algorithm mandates stable sorting, which means elements that compare equal must remain in their original order with respect to each other. This behaviour may not be respected by older browsers.
compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is undefined.
```js
var arr = [1,2,3,4,5,10,9,8,7,6];
arr.sort((a,b)=>a-b); // 升序 ascend
//arr.sort((a,b)=>b-a); // 降序 descend
(10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var arr = [1,2,3,4,5,10,9,8,7,6];
//arr.sort((a,b)=>a-b); // 升序 ascend
arr.sort((a,b)=>b-a); // 降序 descend
(10) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
浏览器行为
Array.sort((a,b)=>{
a - b
});
主流浏览器结果
在老版本Chrome和Firefox下面执行的结果有些不一致,但是新版本做了修正
- Microsoft Edge
版本 93.0.961.47 (官方内部版本) (64 位)
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
VM52:3 (4) ['Dec', 'Feb', 'Jan', 'March']
VM52:8 (5) [1, 100000, 21, 30, 4]
- Chrome Version 93.0.4577.82 (Official Build) (32-bit)
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
VM52:3 (4) ['Dec', 'Feb', 'Jan', 'March']
VM52:8 (5) [1, 100000, 21, 30, 4]
VM147:3 (4) ["Dec", "Feb", "Jan", "March"]
VM147:8
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
Array(4) [ "Dec", "Feb", "Jan", "March" ]
debugger eval code:3:9
Array(5) [ 1, 100000, 21, 30, 4 ]
debugger eval code:8:9
在目前(20210917)最新版本的Chrome和Firefox中两个函数执行的结果呈现一致
内部执行过程
但是在执行过程中 有些不一致
var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"
function sortNumber(a, b) { console.log(a, b); }
document.write(arr + "<br />")
document.write(arr.sort(sortNumber))
var arr = new Array(6)
arr[0] = "a"
arr[1] = "m"
arr[2] = "ll"
arr[3] = "g"
arr[4] = "i"
arr[5] = "t"
function sortNumber(a, b) { console.log(a, b); }
document.write(arr + "<br />")
document.write(arr.sort(sortNumber))
参考
1.关于js中的Array.sort()的使用 2.MDN Array.sort()
|