Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS对APP版本号的比较 #19

Open
akeymo opened this issue May 16, 2020 · 0 comments
Open

JS对APP版本号的比较 #19

akeymo opened this issue May 16, 2020 · 0 comments

Comments

@akeymo
Copy link
Owner

akeymo commented May 16, 2020

思路就是将版本号的每一位拆分成数组,然后从最大位开始比较。如果大于就返回1,小于返回-1,等于返回0。

function compare(version1, version2) {
    if (!version1 || !version2) return false;

    const arr1 = version1.split('.');
    const arr2 = version2.split('.');
    const len1 = arr1.length;
    const len2 = arr2.length;
    const minLen = Math.min(len1, len2);

    let i = 0;
    for (i; i < minLen; i++) {
        const a = parseInt(arr1[i]);
        const b = parseInt(arr2[i]);
        if (a > b) return 1;
        if (a < b) return -1;
    }

    if (len1 > len2) {
        for (let j = i; j < len1; j++) {
            if (parseInt(arr1[j]) !== 0) return 1;
        }

        return 0;
    } else if (len1 < len2) {
        for (let j = i; j < len1; j++) {
            if (parseInt(arr2[j]) !== 0) return -1;
        }

        return 0;
    }

    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant