標籤:資料 io art for 問題 cti
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方法,進而達到了求出最大值的需求。