1.sort的用法

菜鸟教程:

sort() 方法用于对原数组的元素进行排序,默认是按照字符串方式。
排序顺序可以是字母或数字,并按升序或降序。
如果sort中不传入参数,默认排序顺序为按字母升序。

如果想要按照数字排序,则必须传入判断的回调函数。
回调函数有两个参数,分别是数组中相邻的两个元素,
如果回调函数返回值大于0,二者就会交换位置,实现升序,
如果函数返回值小于0,就不做操作。
sort会影响原数组

2.sort使用示例

    const arr = [1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 100, 120, 140]    //默认按照字符串升序,即将数字转换成字符串之后再比较    console.log(arr.sort());//[1, 10, 100, 120,140, 2, 20, 3, 30, 4, 40, 5, 50, 60]    //a是arr[i] b是arr[i+1]    // 返回值是a-b 当a-b>0 即前项大于后项时,二者交换位置 大数值被移到了后面,否则顺序不变 最终实现升序    console.log(arr.sort((a, b) => a - b));//[1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 100, 120, 140]    //返回值是b-a 当后项大于前项时,二者交换顺序,否则顺序不变    console.log(arr.sort((a, b) => b - a));//[140, 120, 100, 60, 50, 40, 30, 20, 10, 5, 4, 3, 2, 1]

3.sort的实现

Array.prototype.mySort = function (cb) {            //如果数组只有一个元素 或者是空数组 不用排序,直接返回即可            if (this.length <= 1) return this            //判断是否传入了回调函数            if (cb === undefined) {                //默认根据字符串大小比较 我采用的是冒泡排序 默认是升序                for (let i = 0; i < this.length; i++) {                    for (let j = 0; j < this.length - i - 1; j++) {                        //将元素强制转换成字符串再比较,如果String(this[j]) > String(this[j + 1]),二者交换位置,否则保持原位置不变                        [this[j], this[j + 1]] =                         String(this[j]) > String(this[j + 1])                         ?                         [this[j + 1], this[j]]                         :                         [this[j], this[j + 1]]                    }                }            //如果传入了一个参数,并且参数是函数,根据函数返回值排序            } else if (cb instanceof Function) {                for (let i = 0; i < this.length; i++) {                    for (let j = 0; j < this.length - i - 1; j++) {                        //cb()>0 升序 cb() <0降序                        //不再直接比较两项元素。而是通过将元素传入回调函数,获得的返回值进行排序                        [this[j], this[j + 1]] = cb(this[j], this[j + 1]) > 0 ? [this[j + 1], this[j]] : [this[j], this[j + 1]]                    }                }                //如果传入了参数,但是参数不是函数,抛出错误            } else {                throw new Error('参数必须是函数')            }            //返回排序之后的数组this            return this        }
仅为个人理解,如有错谬,欢迎指正。
如果对您有所帮助,请您点个赞吧!