手写JS 数组方法之 你不知道的 Array.Sort 方法

86 阅读1分钟

image.png

Sort

  • 官方解释

image.png

  • 参数介绍

image.png

  • 描述

image.png

image.png

手写 Array.Sort

  • 目前实现了 部分功能
  • 返回值为 1 为正序 -1 则为 倒序
  • 参数为空 时进行26 英文字母顺序排序
Array.prototype.mySort = function (callback) {
    const alphabet = 'abcdefghijklmnopqrstuvwxyz';
    const sortArray = this;
    if (!callback) {
        for (let index = 0; index < alphabet.length; index++) {
            for (let juejin = 0; juejin < sortArray.length; juejin++) {
                if (sortArray[juejin][0] === alphabet[index] || sortArray[juejin][0] === alphabet[index].toLocaleUpperCase() ) {
                    const [item] = sortArray.splice(juejin, 1);
                    sortArray.push(item);
                }
            }
        }
        return
    }
    for (let index = 0; index < sortArray.length - 1; index++) {
        for (let juejin = index + 1; juejin < sortArray.length; juejin++) {
            let number = sortArray[index];
            let sort = callback(sortArray[index], sortArray[juejin]) <= 0 ? false : true;
            eval(`if(sortArray[index] ${sort ? '>' : '<'} sortArray[juejin]){
                sortArray[index] = sortArray[juejin];
                sortArray[juejin] = number;
            }`);
        }
    }
}