// 原型链中定义一个自定义比较函数
Array.prototype.customSort = function (compareFunction) {
// sort 就是用来自动排序的
return this.sort(compareFunction);
};
// 使用自定义比较函数排序
const numbers = [5, 2, 8, 1, 4];
numbers.customSort(function (a, b) { return a - b });
console.log(numbers); // 输出: [1, 2, 4, 5, 8]
this.sort() 是数组对象的一个方法,用于原地对数组进行排序操作。
sort() 方法会按照升序对数组的元素进行排序。默认情况下,它将元素转换为字符串,并按照Unicode编码顺序进行排序。
sort() 方法没有返回新的排序后的数组,而是直接修改原始数组。
以下是使用 sort() 方法的基本语法:
array.sort(compareFunction);
compareFunction 是可选的参数,用于指定自定义的排序规则。它是一个比较函数,接受两个参数(通常称为 “a” 和 “b”),并返回一个负数、零或正数,以指示这两个元素的相对顺序。
如果省略 compareFunction 参数,sort() 方法将按照默认的排序规则对数组元素进行排序。
以下是排序示例:
const numbers = [5, 2, 8, 1, 4];
numbers.sort();
console.log(numbers); // 输出: [1, 2, 4, 5, 8]
在上述示例中,我们调用了 sort() 方法,它按照默认规则对数字数组进行升序排序。最终的输出是 [1, 2, 4, 5, 8]。
如果想按照降序进行排序,可以通过提供一个自定义的比较函数来实现:
const numbers = [5, 2, 8, 1, 4];
numbers.sort((a, b) => b - a);
console.log(numbers); // 输出: [8, 5, 4, 2, 1]
在这个示例中,我们通过提供一个比较函数 (a, b) => b - a,将 sort() 方法改为按照降序排序。输出结果为 [8, 5, 4, 2, 1]。
总结起来,this.sort() 方法用于对数组进行原地排序,按照默认规则或自定义的比较函数来确定元素的相对顺序。它会修改原始数组,并返回排序后的数组。
补充一个:
按照字符串长度排序
// 原型链中定义一个自定义排序方法 - 按照字符串长度排序
Array.prototype.sortByLength = function () {
return this.sort((a, b) => a.length - b.length);
};
// 使用自定义排序方法
const strings = ["apple", "banana", "cherry", "date"];
strings.sortByLength();
console.log(strings); // 输出: ["date", "apple", "cherry", "banana"]