`
rguess
  • 浏览: 69630 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类

js扩展一些比较有用的方法

阅读更多
js原型链扩展一些很实用的方法:
/**
 * 格式化日期
 * @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;
};
//使用
alert(new Date().format("yyyy-MM-dd"))
 
/**
 * 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阻止冒泡方法
    }
}


来自个人博客 http://www.rguess.com/blog/article/49.html 求关注
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics