当前位置:   article > 正文

js比较版本号_js判断版本号大小

js判断版本号大小

在实际的开发工作中我们会对项目前后的版本号进行对比,从而进行缓存的更新。下面我们就使用js对标准的版本号进行比较大小。

实现一个方法,用于比较两个版本号(version1、version2)
如果version1 > version2,返回1;
如果version1 < version2,返回-1,
其他情况返回0
版本号规则x.y.z,xyz均为大于等于0的整数,至少有x位

示例:
compareVersion(‘0.1’, ‘1.1.1’); // 返回-1
compareVersion(‘13.37’, '1.2 '); // 返回1
compareVersion(‘1.1’, ‘1.1.0’); // 返回0

function compareVersion(version1, version2) {
    const newVersion1 = `${version1}`.split('.').length < 3 ? `${version1}`.concat('.0') : `${version1}`;
    const newVersion2 = `${version2}`.split('.').length < 3 ? `${version2}`.concat('.0') : `${version2}`;
    //计算版本号大小,转化大小
    function toNum(a){
        const c = a.toString().split('.');
        const num_place = ["", "0", "00", "000", "0000"],
            r = num_place.reverse();
        for (let i = 0; i < c.length; i++){
            const len=c[i].length;
            c[i]=r[len]+c[i];
        }
        return c.join('');
    }

    //检测版本号是否需要更新
    function checkPlugin(a, b) {
        const numA = toNum(a);
        const numB = toNum(b);
        return numA > numB ? 1 : numA < numB ? -1 : 0;
    }
    return checkPlugin(newVersion1 ,newVersion2);
}
compareVersion('0.1', '1.1.1'); // -1
compareVersion('13.37', '1.2 '); // 1
compareVersion('1.1', '1.1.0'); // 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

接下来我们就可以根据这个结果来更新我们的缓存了~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/312431
推荐阅读
相关标签
  

闽ICP备14008679号