<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
//版本比较大小,返回true就是ver1比ver2
function versionCompare (ver1,type,ver2) {
// 将两个版本号拆成数组
let verArr1 = ver1.split('.');
let verArr2 = ver2.split('.');
//取长度最长的
let maxLen = Math.max(verArr1.length, verArr2.length);
let pos = 0; // 当前比较位
let diff = 0; // 当前位比较是否相等
// 逐个比较如果当前位相等则继续比较下一位
while (pos < maxLen) {
diff = parseInt(verArr1[pos]?verArr1[pos]:0) - parseInt(verArr2[pos]?verArr2[pos]:0);
if (diff !== 0) {
break;
}
pos++;
}
switch (type){
case '>=':
return diff >= 0;
case '>':
return diff > 0;
case '<=':
return diff <= 0;
case '<':
return diff < 0;
case '=':
return diff === 0;
default:
return false;
}
}
console.log(versionCompare('1.1.2','>=','1.1.1'))
console.log(versionCompare('1.1.2','=','1.1.1'))
console.log(versionCompare('1.1.2','=','1.1.2'))
console.log(versionCompare('1.1.2','>','1.1.1'))
console.log(versionCompare('1.1.2','<','1.1.1'))
console.log(versionCompare('1.1.2','<=','1.1.1'))
</script>
</body>
</html>
js版本比较简单demo
最新推荐文章于 2024-11-04 16:17:23 发布