作用
对数组进行排序,默认情况下,将元素转换为字符串,然后按照它们的UTF-16码值升序排序。
语法
sort()
元素是字符串时 默认排序时根据字典顺序进行排序的
元素是字母字符串时,按照字母进行升序,
const stringArray = ["Blue", "Humpback", "Beluga"];
console.log(stringArray.sort());
[ 'Beluga', 'Blue', 'Humpback' ]
元素是数字字符串时,将数字转换成ASCII值再进行升序
const numericStringArray = ["80", "9", "700"];
console.log(numericStringArray.sort());
[ '700', '80', '9' ]
元素是数字,按照字符串Unicode的顺序进行排序,而非数值大小。
const numberArray = [40, 1, 5, 200];
console.log(numberArray.sort());
[ 1, 200, 40, 5 ]
const mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];
console.log(mixedNumericArray.sort());
[
1, 200, 40,
5, '700', '80',
'9'
]
sort(compareFn)
function compareBumbers(a,b) {
return a - b
}
const stringArray = ["Blue", "Humpback", "Beluga"];
console.log(stringArray.sort(compareBumbers));
[ 'Blue', 'Humpback', 'Beluga' ]
const numberArray = [40, 1, 5, 200];
console.log(numberArray.sort(compareBumbers));
[ 1, 5, 40, 200 ]
const numericStringArray = ["80", "9", "700"];
console.log(numericStringArray.sort(compareBumbers));
[ '9', '80', '700' ]
const mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];
console.log(mixedNumericArray.sort(compareBumbers));
[
1, 5, '9',
40, '80', 200,
'700'
]
也就是常见的
const a = [2,4,1,6,3,9,5]
console.log(a.sort());
console.log(a.sort((x,y)=>x-y));
元素是对象时,可以通过比较它们的某个属性的值来排序
const items = [
{ name: "Edward", value: 21 },
{ name: "Sharpe", value: 37 },
{ name: "And", value: 45 },
{ name: "The", value: -12 },
{ name: "Magnetic", value: 13 },
{ name: "Zeros", value: 37 },
];
// 根据 value 排序
console.log(items.sort((a, b) => a.value - b.value));
[
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'Zeros', value: 37 },
{ name: 'And', value: 45 }
]