// 比较版本号
// Return 1 if a > b
// Return -1 if a < b
// Return 0 if a == b
function compare(a, b) {
if (a === b) {
return 0;
}
var a_components = a.split(".");
var b_components = b.split(".");
// Math.min(x,y) 返回最低的值
var len = Math.min(a_components.length, b_components.length);
// 组件相等时循环
// loop while the components are equal
for (var i = 0; i < len; i++) {
// A bigger than B
if (parseInt(a_components[i]) > parseInt(b_components[i])) {
return 1;
}
// B bigger than A
if (parseInt(a_components[i]) < parseInt(b_components[i])) {
return -1;
}
}
// If one's a prefix of the other, the longer one is greater.
if (a_components.length > b_components.length) {
return 1;
}
if (a_components.length < b_components.length) {
return -1;
}
// Otherwise they are the same.
return 0;
}
console.log(compare("1", "2")); // -1
console.log(compare("2", "1")); // 1
console.log(compare("1.0", "1.0")); // 0
console.log(compare("2.0", "1.0")); // 1
console.log(compare("1.0", "2.0")); // -1
console.log(compare("1.0.1", "1.0")); // 1