versionCompare °æ±¾ºÅ±È½Ï¹¤¾ß
¼ò½é
ÐèÇó·Ç³£¼òµ¥£¬ÐèÒª±È½ÏÈí¼þ»òappµÄ°æ±¾ºÅ£¬ÅжϴóС£¬ÐÎÈç 0.10.2ÐÎʽµÄ°æ±¾ºÅ×Ö·û´®¡£
ʵÏÖÂß¼ÊÇ°´Õյ㣨.£©·Ö¸î×Ö·û´®£¬È»ºóÖ𼶱Ƚϰ汾´óС¡£
²»´æÔڵİ´0´¦Àí£¬¿Õ×Ö·û´®Ð¡ÓÚ·Ç¿Õ×Ö·û´®¡£
'1' = '1'
'1' = '1.0'
'1' = '1.0.0'
'1.0' = '1'
'1.0' = '1.0'
'1.0.0' = '1.0'
'1.1' > '1'
'1.1' < '1.1.1'
'1.1' = '1.1.0'
'1.1.0' = '1.1'
'0.1.2' < '0.1.2.3'
'0.1.2' < '0.1.3'
'0.1.2' < '0.2.2'
'0.1.2' < '1.1.2'
'10.20.30' = '10.20.30'
'10.20.30' < '10.20.30.0.0.0.1'
'0.10.20.30' < '10.20.30'
'1' > ''
'' < '1'
'' < '0'
'' = ''
Ô´Âë /** * ¶Ô±È×Ö·û´®°æ±¾ºÅµÄ´óС£¬·µ»Ø1Ôòv1´óÓÚv2£¬·µ»Ø-1Ôòv1СÓÚv2£¬·µ»Ø0Ôòv1µÈÓÚv2 * * @author xxcanghai@²©¿ÍÔ° * @param {string} v1 Òª½øÐбȽϵİ汾ºÅ1 * @param {string} v2 Òª½øÐбȽϵİ汾ºÅ2 * @returns */ function versionCompare(v1, v2) { var GTR = 1; //´óÓÚ var LSS = -1; //СÓÚ var EQU = 0; //µÈÓÚ var v1arr = String(v1).split(".").map(function (a) { return parseInt(a); }); var v2arr = String(v2).split(".").map(function (a) { return parseInt(a); }); var arrLen = Math.max(v1arr.length, v2arr.length); var result; //Åųý´íÎóµ÷Óà if (v1 == undefined || v2 == undefined) { throw new Error(); } //¼ì²é¿Õ×Ö·û´®£¬ÈκηǿÕ×Ö·û´®¶¼´óÓÚ¿Õ×Ö·û´® if (v1.length == 0 && v2.length == 0) { return EQU; } else if (v1.length == 0) { return LSS; } else if (v2.length == 0) { return GTR; } //Ñ»·±È½Ï°æ±¾ºÅ for (var i = 0; i < arrLen; i++) { result = xxcanghaiComp(v1arr[i], v2arr[i]); if (result == EQU) { continue; } else { break; } } return result; function xxcanghaiComp(n1, n2) { if (typeof n1 != "number") { n1 = 0; } if (typeof n2 != "number") { n2 = 0; } if (n1 > n2) { return GTR; } else if (n1 < n2) { return LSS; } else { return EQU; } } } ÔÚÏß²âÊÔÒ³Ãæ & Ô´ÂëÏÂÔØDemo:
ËùÓÐÔ´ÂëÏÂÔØGitHub:
https://github.com/xxcanghai/cnblogsFiles/tree/master/versionCompare
posted @
¡¡