如何比较任意版本号? [英] How can I compare arbitrary version numbers?

查看:168
本文介绍了如何比较任意版本号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人在JavaScript中比较两个版本号的代码?我只需要简单的版本比较(例如1.0 vs 1.5.6),数字或字符串。它可以忽略诸如1.5.6b4之类的尾部测试标识符,但是可以预期字符串形式良好。函数应返回一个有符号的整数,像一个正常的cmp函数。

  function cmpVersion(a,b)
return less如果a < b
返回0如果a == b
返回大于1如果一个> b

我有一个答案,但会选择一个更好或更优雅的解决方案。 p>

(我使用这个来比较 jQuery.browser.version 数字,但答案将更广泛适用) / p>

解决方案

  function cmpVersion(a,b){
var i, len,re = /(\.0)+[^\.]*$/;
a =(a +'').replace(re,'').split('。');
b =(b +'').replace(re,'').split('。');
len = Math.min(a.length,b.length);
for(i = 0; i cmp = parseInt(a [i],10) - parseInt(b [i],10)
if(cmp!== 0){
return cmp;
}
}
return a.length - b.length;
}

function gteVersion(a,b){
return cmpVersion(a,b)> = 0;
}
function ltVersion(a,b){
return cmpVersion(a,b) 0;
}

此函数处理:




  • 数字或字符串作为输入

  • 尾随零(例如 cmpVersion(1.0,1) return 0

  • 忽略后面的 alpha b pre4


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 should work with numbers or strings. It can ignore trailing beta identifiers like "1.5.6b4", but can otherwise expect the strings to be well-formed. The function should return a signed integer like a normal cmp function.

function cmpVersion(a, b)
  return less than one if a < b
  return 0 if a == b
  return greater than one if a > b

I have an answer, but will choose a better or more elegant solution over my own.

(I am using this to compare jQuery.browser.version numbers, but the answer will be more widely applicable)

解决方案

function cmpVersion(a, b) {
    var i, cmp, len, re = /(\.0)+[^\.]*$/;
    a = (a + '').replace(re, '').split('.');
    b = (b + '').replace(re, '').split('.');
    len = Math.min(a.length, b.length);
    for( i = 0; i < len; i++ ) {
        cmp = parseInt(a[i], 10) - parseInt(b[i], 10);
        if( cmp !== 0 ) {
            return cmp;
        }
    }
    return a.length - b.length;
}

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

这篇关于如何比较任意版本号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆