以下是软件版本号:

"1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"

我怎么比较呢?

假设正确的顺序是:

"1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"

想法很简单… 读第一个数字,然后,第二个,第三个… 但是我不能将版本号转换为浮点数… 你也可以像这样看到版本号:

"1.0.0.0", "1.0.1.0", "2.0.0.0", "2.0.0.1", "2.0.1.0"

这样可以更清楚地看到背后的想法。 但是,我怎样才能把它转换成计算机程序呢?


当前回答

我喜欢@mar10的版本,尽管从我的角度来看,有误用的可能(如果版本与Semantic Versioning文档兼容,似乎不是这样,但如果使用了一些“构建号”,则可能是这样):

versionCompare( '1.09', '1.1');  // returns 1, which is wrong:  1.09 < 1.1
versionCompare('1.702', '1.8');  // returns 1, which is wrong: 1.702 < 1.8

这里的问题是,在某些情况下,版本号的子数字被删除了后面的零(至少我最近在使用不同的软件时看到的),这类似于数字的有理数部分,因此:

5.17.2054 > 5.17.2
5.17.2 == 5.17.20 == 5.17.200 == ... 
5.17.2054 > 5.17.20
5.17.2054 > 5.17.200
5.17.2054 > 5.17.2000
5.17.2054 > 5.17.20000
5.17.2054 < 5.17.20001
5.17.2054 < 5.17.3
5.17.2054 < 5.17.30

但是,第一个(或第一个和第二个)版本子号始终被视为它实际等于的整数值。

如果你使用这种版本控制,你可以只改变例子中的几行:

// replace this:
p1 = parseInt(v1parts[i], 10);
p2 = parseInt(v2parts[i], 10);
// with this:
p1 = i/* > 0 */ ? parseFloat('0.' + v1parts[i], 10) : parseInt(v1parts[i], 10);
p2 = i/* > 0 */ ? parseFloat('0.' + v2parts[i], 10) : parseInt(v2parts[i], 10);

因此,除了第一个子数字外,每个子数字都将作为浮点数进行比较,因此09和1将相应地变成0.09和0.1,并以这种方式进行正确比较。2054和3将变成0.2054和0.3。

那么,完整的版本是(归功于@mar10):

/** Compare two dotted version strings (like '10.2.3').
 * @returns {Integer} 0: v1 == v2, -1: v1 < v2, 1: v1 > v2
 */
function versionCompare(v1, v2) {
    var v1parts = ("" + v1).split("."),
        v2parts = ("" + v2).split("."),
        minLength = Math.min(v1parts.length, v2parts.length),
        p1, p2, i;
    // Compare tuple pair-by-pair. 
    for(i = 0; i < minLength; i++) {
        // Convert to integer if possible, because "8" > "10".
        p1 = i/* > 0 */ ? parseFloat('0.' + v1parts[i], 10) : parseInt(v1parts[i], 10);;
        p2 = i/* > 0 */ ? parseFloat('0.' + v2parts[i], 10) : parseInt(v2parts[i], 10);
        if (isNaN(p1)){ p1 = v1parts[i]; } 
        if (isNaN(p2)){ p2 = v2parts[i]; } 
        if (p1 == p2) {
            continue;
        }else if (p1 > p2) {
            return 1;
        }else if (p1 < p2) {
            return -1;
        }
        // one operand is NaN
        return NaN;
    }
    // The longer tuple is always considered 'greater'
    if (v1parts.length === v2parts.length) {
        return 0;
    }
    return (v1parts.length < v2parts.length) ? -1 : 1;
}

注:这是比较慢的,但也可以考虑重用相同的比较函数来操作字符串实际上是字符数组的事实:

 function cmp_ver(arr1, arr2) {
     // fill the tail of the array with smaller length with zeroes, to make both array have the same length
     while (min_arr.length < max_arr.length) {
         min_arr[min_arr.lentgh] = '0';
     }
     // compare every element in arr1 with corresponding element from arr2, 
     // but pass them into the same function, so string '2054' will act as
     // ['2','0','5','4'] and string '19', in this case, will become ['1', '9', '0', '0']
     for (i: 0 -> max_length) {
         var res = cmp_ver(arr1[i], arr2[i]);
         if (res !== 0) return res;
     }
 }

其他回答

// Returns true if v1 is bigger than v2, and false if otherwise.
function isNewerThan(v1, v2) {
      v1=v1.split('.');
      v2=v2.split('.');
      for(var i = 0; i<Math.max(v1.length,v2.length); i++){
        if(v1[i] == undefined) return false; // If there is no digit, v2 is automatically bigger
        if(v2[i] == undefined) return true; // if there is no digit, v1 is automatically bigger
        if(v1[i] > v2[i]) return true;
        if(v1[i] < v2[i]) return false;
      }
      return false; // Returns false if they are equal
    }

这就是我的解。它已经在leetcode上被接受。我在今天的面试中遇到了问题。但我当时没有解决它。 我又想了想。加0使两个数组的长度相等。然后比较。

var compareVersion = function(version1, version2) { let arr1 = version1.split('.').map(Number); let arr2 = version2.split('.').map(Number); let diff = 0; if (arr1.length > arr2.length){ diff = arr1.length - arr2.length; while (diff > 0){ arr2.push(0); diff--; } } else if (arr1.length < arr2.length){ diff = arr2.length - arr1.length; while (diff > 0){ arr1.push(0); diff--; } } let i = 0; while (i < arr1.length){ if (arr1[i] > arr2[i]){ return 1; } else if (arr1[i] < arr2[i]){ return -1; } i++; } return 0; };

我也遇到过类似的问题,而且我已经为它创建了一个解决方案。你可以试一试。

如果等于则返回0,如果版本号大于则返回1,如果版本号小于则返回-1

function compareVersion(currentVersion, minVersion) { let current = currentVersion.replace(/\./g," .").split(' ').map(x=>parseFloat(x,10)) let min = minVersion.replace(/\./g," .").split(' ').map(x=>parseFloat(x,10)) for(let i = 0; i < Math.max(current.length, min.length); i++) { if((current[i] || 0) < (min[i] || 0)) { return -1 } else if ((current[i] || 0) > (min[i] || 0)) { return 1 } } return 0 } console.log(compareVersion("81.0.1212.121","80.4.1121.121")); console.log(compareVersion("81.0.1212.121","80.4.9921.121")); console.log(compareVersion("80.0.1212.121","80.4.9921.121")); console.log(compareVersion("4.4.0","4.4.1")); console.log(compareVersion("5.24","5.2")); console.log(compareVersion("4.1","4.1.2")); console.log(compareVersion("4.1.2","4.1")); console.log(compareVersion("4.4.4.4","4.4.4.4.4")); console.log(compareVersion("4.4.4.4.4.4","4.4.4.4.4")); console.log(compareVersion("0","1")); console.log(compareVersion("1","1")); console.log(compareVersion("1","1.0.00000.0000")); console.log(compareVersion("","1")); console.log(compareVersion("10.0.1","10.1"));

const compareAppVersions = (firstVersion, secondVersion) => { const firstVersionArray = firstVersion.split(".").map(Number); const secondVersionArray = secondVersion.split(".").map(Number); const loopLength = Math.max( firstVersionArray.length, secondVersionArray.length ); 对于(设I = 0;i < loopLength;+ + i) { const a = firstVersionArray[i] || 0; const b = secondVersionArray[i] || 0; If (a !== b) { 返回> b ?1: -1; } } 返回0; };

摘自http://java.com/js/deployJava.js:

    // return true if 'installed' (considered as a JRE version string) is
    // greater than or equal to 'required' (again, a JRE version string).
    compareVersions: function (installed, required) {

        var a = installed.split('.');
        var b = required.split('.');

        for (var i = 0; i < a.length; ++i) {
            a[i] = Number(a[i]);
        }
        for (var i = 0; i < b.length; ++i) {
            b[i] = Number(b[i]);
        }
        if (a.length == 2) {
            a[2] = 0;
        }

        if (a[0] > b[0]) return true;
        if (a[0] < b[0]) return false;

        if (a[1] > b[1]) return true;
        if (a[1] < b[1]) return false;

        if (a[2] > b[2]) return true;
        if (a[2] < b[2]) return false;

        return true;
    }