以下是软件版本号:

"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"

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


当前回答

下面是另一个简短的版本,适用于任何数量的子版本,填充零和偶数字母(1.0.0b3)

const compareVer = ((prep, repl) =>
{
  prep = t => ("" + t)
      //treat non-numerical characters as lower version
      //replacing them with a negative number based on charcode of first character
    .replace(/[^0-9\.]+/g, c => "." + (c.replace(/[\W_]+/, "").toLowerCase().charCodeAt(0) - 65536) + ".")
      //remove trailing "." and "0" if followed by non-numerical characters (1.0.0b);
    .replace(/(?:\.0+)*(\.-[0-9]+)(\.[0-9]+)?\.*$/g, "$1$2")
    .split('.');

  return (a, b, c, i, r) =>
  {
    a = prep(a);
    b = prep(b);
    for (i = 0, r = 0, c = Math.max(a.length, b.length); !r && i++ < c;)
    {
      r = -1 * ((a[i] = ~~a[i]) < (b[i] = ~~b[i])) + (a[i] > b[i]);
    }
    return r;
  }
})();

函数返回:

如果a = b则为0

1如果a > b

-1如果a < b

1.0         = 1.0.0.0.0.0
1.0         < 1.0.1
1.0b1       < 1.0
1.0b        = 1.0b
1.1         > 1.0.1b
1.1alpha    < 1.1beta
1.1rc1      > 1.1beta
1.1rc1      < 1.1rc2
1.1.0a1     < 1.1a2
1.1.0a10    > 1.1.0a1
1.1.0alpha  = 1.1a
1.1.0alpha2 < 1.1b1
1.0001      > 1.00000.1.0.0.0.01

/*use strict*/ const compareVer = ((prep, repl) => { prep = t => ("" + t) //treat non-numerical characters as lower version //replacing them with a negative number based on charcode of first character .replace(/[^0-9\.]+/g, c => "." + (c.replace(/[\W_]+/, "").toLowerCase().charCodeAt(0) - 65536) + ".") //remove trailing "." and "0" if followed by non-numerical characters (1.0.0b); .replace(/(?:\.0+)*(\.-[0-9]+)(\.[0-9]+)?\.*$/g, "$1$2") .split('.'); return (a, b, c, i, r) => { a = prep(a); b = prep(b); for (i = 0, r = 0, c = Math.max(a.length, b.length); !r && i++ < c;) { r = -1 * ((a[i] = ~~a[i]) < (b[i] = ~~b[i])) + (a[i] > b[i]); } return r; } })(); //examples let list = [ ["1.0", "1.0.0.0.0.0"], ["1.0", "1.0.1"], ["1.0b1", "1.0"], ["1.0b", "1.0b"], ["1.1", "1.0.1b"], ["1.1alpha", "1.1beta"], ["1.1rc1", "1.1beta"], ["1.1rc1", "1.1rc2"], ["1.1.0a1", "1.1a2"], ["1.1.0a10", "1.1.0a1"], ["1.1.0alpha", "1.1a"], ["1.1.0alpha2", "1.1b1"], ["1.0001", "1.00000.1.0.0.0.01"] ] for(let i = 0; i < list.length; i++) { console.log( list[i][0] + " " + "<=>"[compareVer(list[i][0], list[i][1]) + 1] + " " + list[i][1] ); }

https://jsfiddle.net/vanowm/p7uvtbor/

其他回答

最简单的方法是使用localeCompare:

a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })

这将返回:

0:版本字符串相等 1: a版本大于b版本 -1:版本b大于版本a

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; };

比较不同条件下的功能:

const compareVer = (ver1, middle, ver2) => {
  const res = new Intl.Collator("en").compare(ver1, ver2)
  let comp

  switch (middle) {
    case "=":
      comp = 0 === res
      break

    case ">":
      comp = 1 === res
      break

    case ">=":
      comp = 1 === res || 0 === res
      break

    case "<":
      comp = -1 === res
      break

    case "<=":
      comp = -1 === res || 0 === res
      break
  }

  return comp
}

console.log(compareVer("1.0.2", "=", "1.0.2")) // true
console.log(compareVer("1.0.3", ">", "1.0.2")) // true
console.log(compareVer("1.0.1", ">=", "1.0.2")) // false
console.log(compareVer("1.0.3", ">=", "1.0.2")) // true
console.log(compareVer("1.0.1", "<", "1.0.2")) // true
console.log(compareVer("1.0.1", "<=", "1.0.2")) // true

如果数组包含数字,则可以对数组进行比较。 转换为没有点的数组并比较它们。

函数VersionCompare(version1, version2){ var regExStrip0 = /(\.0+)+$/; var segmentsA = version1。替换(regExStrip0”).split (' . '); var segmentsB = version2。替换(regExStrip0”).split (' . '); if(segmentsA > segmentsB){ 返回1 }else if (segmentsA< segmentsB){ 返回1 其他}{ 返回0 } }

虽然这个问题已经有很多答案,但每个人都在推广自己的解决方案,而我们有一个完整的生态系统(战斗)测试库。

在NPM, GitHub, X上快速搜索会给我们一些可爱的lib,我想要运行一些:

Semver-compare是一个很棒的轻量级库(约230字节),如果您想按版本号排序,它尤其有用,因为库的公开方法会适当地返回-1、0或1。

库的核心:

module.exports = function cmp (a, b) {
    var pa = a.split('.');
    var pb = b.split('.');
    for (var i = 0; i < 3; i++) {
        var na = Number(pa[i]);
        var nb = Number(pb[i]);
        if (na > nb) return 1;
        if (nb > na) return -1;
        if (!isNaN(na) && isNaN(nb)) return 1;
        if (isNaN(na) && !isNaN(nb)) return -1;
    }
    return 0;
};

compare-semver的大小相当大(大约4.4 kB gzip),但是允许进行一些很好的惟一比较,比如查找一堆版本的最小/最大值,或者查找所提供的版本是惟一的还是比版本集合中的其他任何版本都小。

compare-versions是另一个小库(大约630字节gzip),它很好地遵循规范,这意味着你可以比较带有alpha/beta标志甚至通配符的版本(比如minor/patch版本:1.0)。X或1.0)

重点是:如果你能通过你选择的包管理器找到合适的(单元)测试版本,那么并不总是需要从Stack Overflow复制粘贴代码。