How can I compare arbitrary version numbers?

后端 未结 8 1716
半阙折子戏
半阙折子戏 2020-12-06 02:15

Does anyone have code to compare two version numbers in JavaScript? I just want simple version comparisons (e.g. \"1.0\" vs \"1.5.6\"), and it shou

8条回答
  •  攒了一身酷
    2020-12-06 03:09

    function cmpVersion(a, b) {
        var i, cmp, len;
        a = (a + '').split('.');
        b = (b + '').split('.');
        len = Math.max(a.length, b.length);
        for( i = 0; i < len; i++ ) {
            if( a[i] === undefined ) {
                a[i] = '0';
            }
            if( b[i] === undefined ) {
                b[i] = '0';
            }
            cmp = parseInt(a[i], 10) - parseInt(b[i], 10);
            if( cmp !== 0 ) {
                return (cmp < 0 ? -1 : 1);
            }
        }
        return 0;
    }
    
    function gteVersion(a, b) {
        return cmpVersion(a, b) >= 0;
    }
    function ltVersion(a, b) {
        return cmpVersion(a, b) < 0;
    }
    

    This function handles:

    • numbers or strings as input
    • trailing zeros (e.g. cmpVersion("1.0", 1) returns 0)
    • ignores trailing alpha, b, pre4, etc

提交回复
热议问题