1. // 比较版本号
    2. // Return 1 if a > b
    3. // Return -1 if a < b
    4. // Return 0 if a == b
    5. function compare(a, b) {
    6. if (a === b) {
    7. return 0;
    8. }
    9. var a_components = a.split(".");
    10. var b_components = b.split(".");
    11. // Math.min(x,y) 返回最低的值
    12. var len = Math.min(a_components.length, b_components.length);
    13. // 组件相等时循环
    14. // loop while the components are equal
    15. for (var i = 0; i < len; i++) {
    16. // A bigger than B
    17. if (parseInt(a_components[i]) > parseInt(b_components[i])) {
    18. return 1;
    19. }
    20. // B bigger than A
    21. if (parseInt(a_components[i]) < parseInt(b_components[i])) {
    22. return -1;
    23. }
    24. }
    25. // If one's a prefix of the other, the longer one is greater.
    26. if (a_components.length > b_components.length) {
    27. return 1;
    28. }
    29. if (a_components.length < b_components.length) {
    30. return -1;
    31. }
    32. // Otherwise they are the same.
    33. return 0;
    34. }
    35. console.log(compare("1", "2")); // -1
    36. console.log(compare("2", "1")); // 1
    37. console.log(compare("1.0", "1.0")); // 0
    38. console.log(compare("2.0", "1.0")); // 1
    39. console.log(compare("1.0", "2.0")); // -1
    40. console.log(compare("1.0.1", "1.0")); // 1