Created
January 20, 2014 11:00
-
-
Save puterjam/8518259 to your computer and use it in GitHub Desktop.
判断版本号大小
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 判断两个版本字符串的大小 | |
* @param {string} v1 原始版本 | |
* @param {string} v2 目标版本 | |
* @return {number} 如果原始版本大于目标版本,则返回大于0的数值, 如果原始小于目标版本则返回小于0的数值。0当然是两个版本都相等拉。 | |
*/ | |
function compareVersion(v1, v2) { | |
var _v1 = v1.split("."), | |
_v2 = v2.split("."), | |
_r = _v1[0] - _v2[0]; | |
return _r == 0 && v1 != v2 ? compareVersion(_v1.splice(1).join("."), _v2.splice(1).join(".")) : _r; | |
} | |
console.log(compareVersion("1.2.33.6", "1.2.33.6.7")); //-7 | |
console.log(compareVersion("1.0", "1.0.1")); //-1 | |
console.log(compareVersion("1.0", "0.0.5")); //1 |
export function compareVersion (v1 = '', v2 = '') {
let _v1 = v1.split('.'),
_v2 = v2.split('.'),
// 或操作是为了占位,避免NaN
_r = parseInt(_v1[0] || 0, 10) - parseInt(_v2[0] || 0, 10);
return v1 !== v2 && _r === 0 ? compareVersion(_v1.splice(1).join('.'), _v2.splice(1).join('.')) : _r;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
非常好用.