您现在的位置是:网站首页 > 心得笔记

JavaScript实现版本号比较

盛悦2019-10-0915人围观
简介JavaScript实现版本号比较

                /* 
                 * JavaScript实现版本号比较
                 * 传入两个字符串,当前版本号:curV;比较版本号:reqV 
                 * 调用方法举例:Version('5.12.3','5.12.2'),将返回true
                 */
                
                Version('5.12.3','5.12.2')
                
                function Version(curV,reqV){
                    
                    var arr1=curV.split('.');
                    var arr2=reqV.split('.');
                    //将两个版本号拆成数字 
                    var minL= Math.min(arr1.length,arr2.length);  
                    var pos=0;        //当前比较位
                    var diff=0;        //当前为位比较是否相等
                    
                    //逐个比较如果当前位相等则继续比较下一位
                    while(pos<minL){
                        diff=parseInt(arr1[pos])-parseInt(arr2[pos]);  
                        if(diff!=0){  
                          break;  
                        } 
                        pos++;                  
                    }
                    
                    if (diff>0) {
                        console.log('新版本')
                    }else if (diff==0) {
                        console.log('稳定版')
                    }else{
                        console.log('旧版本')
                    }