借用原型链补充数组的高阶排序方法

        // 原型链中定义一个自定义比较函数
        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"]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值