nodejs實(shí)現(xiàn)版本號(hào)比較

一般程序版本號(hào)形式x.x.x.x的字符串,例如:1.0、1.0.0、1.0.0.0。如果直接采用字符串比較大小,會(huì)出現(xiàn)低版本大于高版本的結(jié)果,例如:1.10.1和1.9.2比較,就會(huì)出現(xiàn)"1.9.2" > "1.10.1"。所以需要對(duì)于每一位分開,采用補(bǔ)位的方式逐個(gè)比較。

function compairVersion (v1, v2) {
    //補(bǔ)位0,或者使用其它字符
    const ZERO_STR = '000000000000000000000000000000000000000000';
    if (v1 === v2) {
        return 0;
    }
    let len1 = v1 ? v1.length : 0;
    let len2 = v2 ? v2.length : 0;
    if ( len1 === 0 && len2 === 0) {
        return 0;
    }
    if (len1 === 0) {
        return 1;
    }
    if (len2 === 0) {
        return -1;
    }
    const arr1 = v1.split('.');
    const arr2 = v2.split('.');
    const length = Math.min(arr1.length, arr2.length);
    for (let i = 0; i < length; i++) {
        let a = arr1[i];
        let b = arr2[i];
        if (a.length < b.length) {
            a = ZERO_STR.substr(0, b.length - a.length) + a;
        } else if (a.length > b.length) {
            b = ZERO_STR.substr(0, a.length - b.length) + b;
        }
        if (a < b) {
            return 1;
        } else if (a > b) {
            return -1;
        }
    }
    if (arr1.length < arr2.length) {
        return 1;
    } else if (arr1.length > arr2.length) {
        return -1;
    }
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容