【问题标题】:Javascript if statement with numbers that have multiple decimals带有多个小数的数字的 Javascript if 语句
【发布时间】:2014-03-21 16:50:45
【问题描述】:

出于网站支持的原因,我正试图弄清楚如何检测浏览器的浏览器版本。我想知道浏览器是否比 3.6.1 更好,那么浏览器是好的,否则显示错误。

问题是我只能用小数点后一位,必须有办法做到这一点。

我尝试过parseFloat("3.6.28"),但它只给了我 3.6。

我该怎么做:

if(3.5.1 > 3.5.0)
{
//Pass!
}

【问题讨论】:

  • 3.5.1 实际上不是一个数字,因此没有内置任何东西可以将其视为数字(这就是为什么 parseFloat 不起作用的原因)。不确定 javascript 中是否存在任何类型的“版本”对象,但我在这里可能会采用拆分和分段比较。
  • 创建一个你的对象与你的函数进行比较

标签: javascript math browser numbers decimal


【解决方案1】:

如果您会大量使用版本,那么可能值得编写这样的内容

function Version(str) {
    var arr = str.split('.');
    this.major    = +arr[0] || 0;
    this.minor    = +arr[1] || 0;
    this.revision = +arr[2] || 0; // or whatever you want to call these
    this.build    = +arr[3] || 0; // just in case
    this.toString();
}
Version.prototype.compare = function (anotherVersion) {
    if (this.toString() === anotherVersion.toString())
        return 0;
    if (
        this.major > anotherVersion.major ||
        this.minor > anotherVersion.minor ||
        this.revision > anotherVersion.revision ||
        this.build > anotherVersion.build
    ) {
        return 1;
    }
    return -1;
};
Version.prototype.toString = function () {
    this.versionString = this.major + '.' + this.minor + '.' + this.revision;
    if (this.build)
        this.versionString += '.' + this.build;
    return this.versionString;
};

现在

var a = new Version('3.5.1'),
    b = new Version('3.5.0');
a.compare(b); //  1 , a is bigger than b
b.compare(a); // -1 , b is smaller than a
a.compare(a); //  0 , a is the same as a

否则只使用你需要的位

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2021-12-16
    相关资源
    最近更新 更多