How can I compare arbitrary version numbers?

后端 未结 8 1758
半阙折子戏
半阙折子戏 2020-12-06 02:15

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 shou

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 03:05

    function compareVersion(a, b) {
        return compareVersionRecursive(a.split("."), b.split("."));
    }
    
    function compareVersionRecursive(a, b) {
        if (a.length == 0) {
            a = [0];
        }
        if (b.length == 0) {
            b = [0];
        }
        if (a[0] != b[0] || (a.length == 1 && b.length == 1)) {
            return a[0] - b[0];
        }
        return compareVersionRecursive(a.slice(1), b.slice(1));
    }
    

提交回复
热议问题