sort():对数组的元素进行排序,改变原数组。
它可以传递一个定义排序顺序的函数作为参数。
如果没有传递参数,则进行默认排序。默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序。
对于sort的默认排序,我也进行了重写:
// 没有传递compareFn时,数组元素会被转换为字符串,然后按照每个字符的Unicode码进行排序
function compareUnicode(str1, str2) {
// String()将数组元素会被转换为字符串
let str11=String(str1)
let str22=String(str2)
let len1 = str11.length;
let len2 = str22.length;
let minLength = Math.min(len1, len2);
// 逐字符比较UTF-16码点
for (let i = 0; i < minLength; i++) {
let codeUnit1 = str11.charCodeAt(i);
let codeUnit2 = str22.charCodeAt(i);
if (codeUnit1 < codeUnit2) {
return -1; // str1在str2之前
} else if (codeUnit1 > codeUnit2) {
return 1; // str1在str2之后
}
}
// 如果所有已比较字符都相同,则比较字符串长度
return len1 - len2;
}
重写的sort方法如下:
// sort:以字母顺序对数组进行排序,改变原数组
Array.prototype.mySort = function (compareFn = compareUnicode) {
// 如果传递了compareFn,但不是一个函数
if (typeof compareFn !== "function") {
throw new TypeError(
"The comparison function must be either a function or undefined"
);
}
// 排序
for (let i = 0; i < this.length; i++) {
for (let j = 0; j < this.length; j++) {
if (j == this.length - 1) {
break;
}
if (compareFn(this[j], this[j + 1]) > 0) {
// this[j]>this[j+1]
[this[j], this[j + 1]] = [this[j + 1], this[j]];
}
}
}
return this;
};