JavaScript 中的中文数字排序算法 - 优化版
function compare(a, b) {/n // 使用正则表达式提取出中文和数字/n var pattern = /([/u4e00-/u9fa5]+)(/d+)/;/n var aMatch = a.location ? a.location.match(pattern) : null;/n var bMatch = b.location ? b.location.match(pattern) : null;/n/n // 判断是否有空的location/n if (a.location === null && b.location === null) {/n // 如果两个字段都为空,则位置不变/n return 0;/n } else if (a.location === null) {/n // 如果a的字段为空,则b的字段在前/n return 1;/n } else if (b.location === null) {/n // 如果b的字段为空,则a的字段在前/n return -1;/n } else {/n // 如果都不为空,则按照原来的逻辑进行排序/n if (aMatch === null && bMatch === null) {/n // 如果两个字段都不满足正则表达式的匹配条件,则直接比较原始字段/n return a.location.localeCompare(b.location);/n } else if (aMatch === null) {/n // 如果a的字段不满足正则表达式的匹配条件,则b的字段在前/n return -1;/n } else if (bMatch === null) {/n // 如果b的字段不满足正则表达式的匹配条件,则a的字段在前/n return 1;/n } else {/n // 先比较中文,如果中文相同再比较数字/n if (aMatch[1] < bMatch[1]) {/n return -1;/n } else if (aMatch[1] > bMatch[1]) {/n return 1;/n } else {/n return parseInt(aMatch[2]) - parseInt(bMatch[2]);/n }/n }/n }/n}/n
原文地址: https://www.cveoy.top/t/topic/d846 著作权归作者所有。请勿转载和采集!