初步简单实现sort方法,有助于深刻理解和记忆
Array.prototype.savaSort = function (fn) {
for (let i = 0, len = this.length; i < len - 1; i++) {
for (let j = i + 1; j < len; j++) {
if (arguments.length > 0) {
if (fn(this[i], this[j]) > 0) {
let temp = this[i]
this[i] = this[j]
this[j] = temp
}
} else {
if (this[i] > this[j]) {
let temp = this[i]
this[i] = this[j]
this[j] = temp
}
}
}
}
}
var arr = [9, 7, 8, 4, 5, 6]
//传参
arr.savaSort(function(a,b){
return b-a
})
console.log(arr) //[ 9, 8, 7, 6, 5, 4 ]
//不传参
arr.savaSort()
console.log(arr) //[ 4, 5, 6, 7, 8, 9 ]