版本对比
对比版本:
判断版本v2是否大于等v1版本,如果大于则返回true,否则返回false
方法1:
// comparedVersion('1.23.3', '2.45.3')
function comparedVersion (a, b) { if (a == b) { return true; } if (!a) { return console.error('没有拿到app版本号') } const aobj = a.split('.'); const bobj = b.split('.'); for (var i = 0; i < 3; i++) { if (bobj[i] * 1 == aobj[i] * 1) { continue; } if (bobj[i] * 1 > aobj[i] * 1) { return true; } else { return false; } } return false; }
方法2:
// comparedVersion('1.23.3', '2.45.3')
function comparedVersion(v1, v2) { if (!v1) { return 0; } let maxLen = 0; let firstVersion = v1.split('.'); let lastVersion = v2.split('.'); maxLen = firstVersion.length > lastVersion.length ? firstVersion.length : lastVersion.length; return formatVersion(lastVersion, maxLen) >= formatVersion(firstVersion, maxLen); // 格式化版本(实现思路:将数组所有想都在前面补0,每项补足长度为4,然后拼接成数组,最后转换为数字,数字越大则版本号越大) // 示例:['2', '12', '34'] 格式化为 200120034 // 示例:['12', '2', '34'] 格式化为 1200020034 function formatVersion(versionArray, hierarchy) { let result = ''; let loop = new Array(hierarchy).fill(1); loop.forEach((s, i)=>{ let len = '0000'; if(versionArray[i] && versionArray[i].length < len.length){ result += len.substring(0, len.length - versionArray[i].length) + versionArray[i]; } else { result += len; } console.log(result); }); return Number(result); } }