Js基本数据类型常用方法扩展

时间:2014-07-22 22:56:13   收藏:0   阅读:269

1.    Array的contains方法

Array没有一个contains方法,在现实的应用场景是,有时候我们需要判断某一个值是否

在该数组中,这个时候一个contains方法就显得很有必要,具体实现如下:

//判断数组中是否包含某个元素

Array.prototype.contains = function (obj) {

    var i = this.length;

    while (i--) {

        if (this[i] === obj) {

            return true;

        }

    }

    return false;

}

2.    String的contains方法

同样的问题也存在于String类型中,在js中同样也没有一个用来判断某一子串是否包

含在母字符串中的方法,具体实现如下:

//字符串中是否包含某字符串

String.prototype.contains = function contains(string, substr, isIgnoreCase) {

    if (isIgnoreCase) {

        this = this.toLowerCase();

        string = string.toLowerCase();

        substr = substr.toLowerCase();

    }

    var startChar = substr.substring(0, 1);

    var strLen = substr.length;

    for (var j = 0; j < string.length - strLen + 1; j++) {

        if (string.charAt(j) == startChar)//

        {

            if (string.substring(j, j + strLen) == substr)//

            {

                return true;

            }

        }

    }

    return false;

3.    Date的addDays、addMonths、addYear、Format方法

熟悉C#的朋友,都会很熟悉也很享受关于DateTime的一系列的便利的操作,在js中并

没有像C#中那样便利的有关时间的操作,有时候不免会用到时间的加减等相关的交互,这里专门对Date类型进行了扩展,具体如下:

//添加天

Date.prototype.addDays = function (d) {

    this.setDate(this.getDate() + d);

};

 

//添加周

Date.prototype.addWeeks = function (w) {

    this.addDays(w * 7);

};

 

//添加月

Date.prototype.addMonths = function (m) {

    var d = this.getDate();

    this.setMonth(this.getMonth() + m);

 

    if (this.getDate() < d)

        this.setDate(0);

};

//添加年

Date.prototype.addYears = function (y) {

    var m = this.getMonth();

    this.setFullYear(this.getFullYear() + y);

 

    if (m < this.getMonth()) {

        this.setDate(0);

    }

};

//日期的格式处理

//日期格式化

Date.prototype.Format = function (fmt) { //author: meizz   

    var o = {

        "M+": this.getMonth() + 1,                 //月份   

        "d+": this.getDate(),                    //日   

        "h+": this.getHours(),                   //小时   

        "m+": this.getMinutes(),                 //分   

        "s+": this.getSeconds(),                 //秒   

        "q+": Math.floor((this.getMonth() + 3) / 3), //季度

        "S": this.getMilliseconds()             //毫秒   

    };

    if (/(y+)/.test(fmt))

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

    for (var k in o)

        if (new RegExp("(" + k + ")").test(fmt))

            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

    return fmt;

};

4.    Math.max.apply(null,array),求数组中的最大值

该方法主要用来求一个数组中的最大值,这种场景在实际的工作中也会经常用遇到。或

许会有朋友问到,为什么不直接调用Math.max()方法?需要注意的是Math.max()方法支持多个参数的传递,但是它不支持直接传递一个数组作为参数,但是所有的函数都有apply(作用域,参数)这样的一个方法,我们通过apply方法,间接的将数组作为参数,并且将数组中的每个值拆开来传递给了max方法,进而达到了求出最大值的需求。

Js基本数据类型常用方法扩展,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!