How can I compare arbitrary version numbers?

后端 未结 8 1710
半阙折子戏
半阙折子戏 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:17

    This function returns true if the version is greater than or equal to the minimum version. Assumes 1.0 is greater than 1 when versions are strings. When they are numbers it says they are the same. If you want to have both types return the same then you need to convert the numbers to strings which is also easy. or you can modify the string condition to check if the longer version number has all trailing zeros like 1.1 vs 1.1.0.0.0.0. the second one is all trailing zeros

     function doesMyVersionMeetMinimum(myVersion, minimumVersion) {
    
        if(typeof myVersion === 'number' && typeof minimumVersion === 'number') {
          return(myVersion >= minimumVersion);
        }
    
        var v1 = myVersion.split("."), v2 = minimumVersion.split("."), minLength;
    
        minLength= Math.min(v1.length, v2.length);
    
        for(i=0; i<minLength; i++) {
            if(Number(v1[i]) < Number(v2[i])) {
                return false;
            }
           else if(Number(v1[i]) < Number(v2[i])) {
                return true;
            }           
    
        }
    
        return (v1.length >= v2.length);
    }
    
    0 讨论(0)
  • 2020-12-06 03:19

    If you want to be fully correct, take a look at the discussion on PEP386, especially the heading “the new versioning algorithm”.

    Otherwise it seems like your answer is pretty good.

    0 讨论(0)
提交回复
热议问题