// 方法一:从左到右迭代,从高位判断,返回高位的大小结果 注意:仅适用于版本号各个位的位数相同 let versions = ["1.45.0", "1.5", "6", "2.3.4.5"]; versions = versions.sort((a, b) => { let arr1 = a.split('.'); let arr2 = b.split('.'); let i = 0; while (true) { let s1 = arr1[i]; let s2 = arr2[i]; i++; if (s1 == undefined || s2 == undefined) { return arr1.length - arr2.length; } if (s1 == s2) { continue; } return s1 - s2; } }) console.log(versions); //[ '1.5', '1.45.0', '2.3.4.5', '6' ] // 方法二:全部转为小数,比小数的大小,注意:仅适用于版本号各个位的位数相同 let arr = ["3.1.4.512", "0.2.5.4", "0.2.23.456", "0.3.456", "1.0"]; arr.sort((a, b) => { return Number("0." + a.split(".").join("")) - Number("0." + b.split(".").join("")); }); console.log(arr); //[ '0.2.23.456', '0.2.5.4', '0.3.456', '1.0', '3.1.4.512' ]
参考链接:https://blog.csdn.net/jiong9412/article/details/124776279
// 方法三,通过 点 将版本号分割为数组,如果版本号长度不同,则填入 0,分别比较每一位的大小,可以准确判断每一位的大小 let compareVersion = function (v1, v2) { // console.log({v1, v2}) if (typeof v1 === "undefined" || typeof v2 === "undefined") { console.error('请指定要对比的两个版本号', {v1, v2}) return } v1 = v1.split('.') v2 = v2.split('.') const maxLength = Math.max(v1.length, v2.length) // 补全 while (v1.length < maxLength) { v1.push('0') } while (v2.length < maxLength) { v2.push('0') } for (let i = 0; i < maxLength; i++) { let num1 = parseInt(v1[i]) let num2 = parseInt(v2[i]) if (num1 > num2) { return 1 } else if (num1 < num2) { return -1 } } return 0 } compareVersion('0.5.1','0.302.1') // -1 , 说明前者小于后者
标签:return,版本号,length,js,v1,v2,let,排序 From: https://www.cnblogs.com/beileixinqing/p/17012508.html