【问题标题】:How to compare strings "17.4.0.50" and "3.1.0.114" using javascript? [duplicate]如何使用javascript比较字符串“17.4.0.50”和“3.1.0.114”? [复制]
【发布时间】:2020-12-20 12:25:08
【问题描述】:

我尝试比较以下字符串。但我无法得到正确答案。

    var a = "17.4.0.50";
    var b = "3.1.0.114";
    
    if(a>b){
    alert("a is greater than b");
    }
    else{
    alert("b is greater than a");
    }

得到“b大于a”的结果。

谁能帮我得到正确的结果?

提前致谢,

【问题讨论】:

  • 您会使用哪些规则来比较 IP 地址?这不是我们通常比较的东西。

标签: javascript comparison string-comparison


【解决方案1】:

您似乎正在尝试比较版本。这是我的建议

//Need to compute the common minimum patch version place
var numPatchIdentifiersArray = new Array();
var aPatches = a.split(".")
var bPatches = b.split(".")

numPatchIdentifiersArray.push(aPatches.length);
numPatchIdentifiersArray.push(bPatches.length);

var minNumPatchIdentifiers = min(numDecimalsArray);

for (var index = 0; index < minNumPatchIdentifiers; index++) {
    if (parseInt(aPatches[index]) > parseInt(bPatches[index])) {
        console.log("a > b");
        break;
    } else if (parseInt(aPatches[index]) < parseInt(bPatches[index])) {
        console.log("a < b");
        break;
    } 
}

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 2017-09-18
    • 2017-06-27
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多