首页 > 语言 > JavaScript > 正文

基于prototype扩展的JavaScript常用函数库

2024-05-06 14:26:21
字体:
来源:转载
供稿:网友
代码如下:
/**
2 * 检索数组元素(原型扩展或重载)
3 * @param {o} 被检索的元素值
4 * @type int
5 * @returns 元素索引
6 */
7 Array.prototype.contains = function(o) {
8 var index = -1;
9 for(var i=0;i<this.length;i++){if(this[i]==o){index = i;break;}}
return index;
}

/**
* 日期格式化(原型扩展或重载)
* 格式 YYYY/yyyy/YY/yy 表示年份
* MM/M 月份
* W/w 星期
* dd/DD/d/D 日期
* hh/HH/h/H 时间
* mm/m 分钟
* ss/SS/s/S 秒
* @param {formatStr} 格式模版
* @type string
* @returns 日期字符串
*/
Date.prototype.format = function(formatStr){
var str = formatStr;
var Week = ['日','一','二','三','四','五','六'];
str=str.replace(/yyyy|YYYY/,this.getFullYear());
str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));
str=str.replace(/MM/,(this.getMonth()+1)>9?(this.getMonth()+1).toString():'0' + (this.getMonth()+1));
str=str.replace(/M/g,this.getMonth());
str=str.replace(/w|W/g,Week[this.getDay()]);
str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());
str=str.replace(/d|D/g,this.getDate());
str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());
str=str.replace(/h|H/g,this.getHours());
str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());
str=str.replace(/m/g,this.getMinutes());
str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());
str=str.replace(/s|S/g,this.getSeconds());
return str;
}

/**
* 比较日期差(原型扩展或重载)
* @param {strInterval} 日期类型:'y、m、d、h、n、s、w'
* @param {dtEnd} 格式为日期型或者 有效日期格式字符串
* @type int
* @returns 比较结果
*/
Date.prototype.dateDiff = function(strInterval, dtEnd) {
var dtStart = this;
if (typeof dtEnd == 'string' ) { //如果是字符串转换为日期型
dtEnd = StringToDate(dtEnd);
}
switch (strInterval) {
case 's' :return parseInt((dtEnd - dtStart) / 1000);
case 'n' :return parseInt((dtEnd - dtStart) / 60000);
case 'h' :return parseInt((dtEnd - dtStart) / 3600000);
case 'd' :return parseInt((dtEnd - dtStart) / 86400000);
case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));
case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);
case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();
}
}

/**
* 日期计算(原型扩展或重载)
* @param {strInterval} 日期类型:'y、m、d、h、n、s、w'
* @param {Number} 数量
* @type Date
* @returns 计算后的日期
*/
Date.prototype.dateAdd = function(strInterval, Number) {
var dtTmp = this;
switch (strInterval) {
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选