作为前端一枚小萌新,每次用到sort都是一脸懵,所以这次决定手写js的sort的方法,来加深自己对其的理解。
下面这样的代码大家应该都见过,我第一次看到的时候是超级困惑
let arr = [2, 5, 7, 4, 11];
arr.sort();
//结果返回的是[11, 2, 4, 5, 7]
应为sort函数在没有参数是根据ASCII进行排序的,11的十位数是最低的,所以排在最前面。这时候我们需要写一个回调函数的形参来实现真正的升序排序
let arr = [2, 5, 7, 4, 11];
arr.sort(function(a, b) {return a-b});
//返回[2, 4, 5, 7, 11]
arr.sort(function(a, b) {return b-a});
//返回[11, 7, 5, 4, 2]
我当时看到这个回调函数,每次都是似懂非懂,不是很明白其中原理,但是知道是操纵排序的,于是我写了下面这个函数。当时使用循环时,首当其冲想到的是for...of,但是基本类型的地址空间是不一致,引用类型给的是地址所以才能起作用,所以后面用for...in了。
let random = [5, 3, 4, 6, 3, 8, 15];
Array.prototype.sortBubble = function(callback) {
for (const n in this) {
for (const m in this) {
if(callback(this[n], this[m]) < 0) {
const temp = this[n];
this[n] = this[m];
this[m] = temp;
}
}
}
return this;
}
random.sortBubble(function(a, b) {return b - a;});
console.log(random); //[3, 3, 4, 5, 6, 8, 15]
时间复杂度挺大的,具体优化以后再实现吧