1、回调函数(callback)
MDN 的描述
回调函数是作为参数传给另一个函数的函数,然后通过在外部函数内部调用该回调函数以完成某种操作。
个人理解
回调函数就是一个函数使用了另一个函数作为参数,然后在内部使用该函数,从而可以增强函数的功能,也就是根据传入的函数,一个函数可以实现许多功能。例如接下来的Array.sort(),可以根据传入的函数参数,实现正序或者逆序排序。
2、Array.sort()
截图来自MDN
3、手写Array.sort()
代码如下,只是简单的利用回调函数实现了数值数组的正序和逆序的排序,实际的源码要复杂的多。
const mySort = function(callback) {
for(let i=0 ; i< this.length; i++){
for(let j=0; j < this.length - i -1; j++){
if(callback(this[j],this[j+1]) > 0){
let temp = this[j];
this[j] = this[j+1];
this[j+1] = temp;
}
}
}
return this;
}
Array.prototype.mySort = mySort;
const arr = [5,3,1,2,4]
//正序:(a,b) => a - b)
//逆序:(a,b) => b - a)
console.log(arr.mySort((a,b) => a - b));
arr.mySort((a,b) => a - b)
其中(a,b) => a - b
便是回调函数,在mySort函数中调用它来实现排序规则。