如果没有提供比较函数作为参数,sort() 方法会将数组元素转换为字符串,然后按照字符串的 Unicode 编码进行排序。这意味着对于数字,它们会先被转换为字符串,然后按照字符串的排序规则进行排序。
比较函数是可选的,并且允许您自定义排序规则。比较函数应该接受两个参数(通常被称为a和b),并返回以下值之一:
如果a应该排在b之前,则返回一个负数。
如果a应该排在b之后,则返回一个正数。
如果a和b相等,或者它们的排序顺序不重要,则返回 0。
以下是sort() 方法的示例用法:
const numbers = [5, 1, 3, 2, 4];
numbers.sort(); // 默认排序
console.log(numbers); // 输出: [1, 2, 3, 4, 5]
const strings = ['banana', 'apple', 'cherry'];
strings.sort(); // 默认排序
console.log(strings); // 输出: ['apple', 'banana', 'cherry']
const objects = [
{ name: 'John', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
objects.sort((a, b) => a.age - b.age); // 根据 age 属性排序
console.log(objects);
// 输出:
// [
// { name: 'Alice', age: 25 },
// { name: 'John', age: 30 },
// { name: 'Bob', age: 35 }
// ]
如果想要不改变原数组的排序方法,可以使用 toSorted()。
Array 实例的 toSorted() 方法是 sort() 方法的复制方法版本。它返回一个新数组,其元素按升序排列。
const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']
const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b));
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]