javascript实现的字符串排序
2021-6-28 9:40网上查了下没有现成的按照常规排序的方法,自己写了一个。逻辑是如果不是汉字按照字符的值的大小排序,如果是汉字就按照汉字的拼音排序。
stringCompare (str1, str2) { let i = 0; for (; i < str1.length; i++) { let code1 = str1.charCodeAt(i); let code2 = str2.charCodeAt(i); if (isNaN(code1) && isNaN(code2)) { return 0; } if (isNaN(code1)) { return -1; } if (isNaN(code2)) { return 1; } if (code1 === code2) { continue; } if (code1 > 0x4e00 && code2 > 0x4e00) { return str1.charAt(i).localeCompare(str2.charAt(i)); } else { return code1 - code2; } } if (str1.length === str2.length) { return 0; } return -1; }