javascript常用工具函數

phpw34 9年前發布 | 939 次閱讀 JavaScript

 
/**

  • 格式化日期
  • @param format
  • @returns */ Date.prototype.format = function(format) { var o = {

     "M+" : this.getMonth() + 1, // month
     "d+" : this.getDate(), // day
     "h+" : this.getHours(), // hour
     "m+" : this.getMinutes(), // minute
     "s+" : this.getSeconds(), // second
     "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
     "S" : this.getMilliseconds()
    

    // millisecond };

    if (/(y+)/.test(format)) {

     format = format.replace(RegExp.$1, (this.getFullYear() + "")
             .substr(4 - RegExp.$1.length));
    

    }

    for ( var k in o) {

     if (new RegExp("(" + k + ")").test(format)) {
         format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                 : ("00" + o[k]).substr(("" + o[k]).length));
     }
    

    } return format; };

/**

  • 日期相減
  • @param sDate1
  • @param sDate2
  • @returns */ function DateDiff(sDate1,sDate2) { var arrDate,objDate1,objDate2,intDays; arrDate=sDate1.split("-"); objDate1=new Date(arrDate[1]+'-'+arrDate[2]+'-'+arrDate[0]); arrDate=sDate2.split("-"); objDate2=new Date(arrDate[1] + '-'+arrDate[2]+'-'+arrDate[0]); intDays=parseInt(Math.abs(objDate1-objDate2)/1000/60/60/24); return intDays; }

/**

  • js原型鏈實現replaceAll */ String.prototype.replaceAll = function(s1,s2){ return this.replace(new RegExp(s1,"gm"),s2); };

/**

  • js實現endWith */ String.prototype.endWith=function(str){ if(str==null||str==""||this.length==0||str.length>this.length) return false; if(this.substring(this.length-str.length)==str) return true; else return false; return true; }

/**

  • js實現startWith */ String.prototype.startWith=function(str){ if(str==null||str==""||this.length==0||str.length>this.length) return false; if(this.substr(0,str.length)==str) return true; else return false; return true; }

/**

  • 數組擴展---根據下標刪除某元素 */ Array.prototype.del=function(n) { if(n<0) return this; else
     return this.slice(0,n).concat(this.slice(n+1,this.length));
    
    };

/**

  • 數組擴展---根據一個值刪除某元素 */ Array.prototype.delByValue=function(value) { for(var i = 0;i<this.length;i++){
     if(this[i] == value){
         this.del(i);
     }
    
    } };

/**

  • 數組擴展判斷某值知否在數組中 */ Array.prototype.isContainsValue=function(value) { for(var i in this){
     if(this[i]==value){
         return true;
     }
    
    } return false; };

/**

  • js阻止冒泡事件 */ function stopPropagation(e) { e = e || window.event; if(e.stopPropagation) { //W3C阻止冒泡方法
     e.stopPropagation();
    
    } else {
     e.cancelBubble = true; //IE阻止冒泡方法
    
    } } </pre>
 本文由用戶 phpw34 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!