另:只要内置对象的原型(prototype)函数。
42 个解决方案
#1
自己先顶:
String对象的几个原型方法:
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
};
String.prototype.ltrim = function(){
return this.replace(/(^\s*)/g, "");
};
String.prototype.rtrim = function(){
return this.replace(/(\s*$)/g, "");
};
//取字符串第一个字符的 Unicode 编码
String.prototype.ascii = function(){
return this.charCodeAt(0);
};
String.prototype.endsWith = function(character){
return (character == this.charAt(this.length - 1));
};
String对象的几个原型方法:
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
};
String.prototype.ltrim = function(){
return this.replace(/(^\s*)/g, "");
};
String.prototype.rtrim = function(){
return this.replace(/(\s*$)/g, "");
};
//取字符串第一个字符的 Unicode 编码
String.prototype.ascii = function(){
return this.charCodeAt(0);
};
String.prototype.endsWith = function(character){
return (character == this.charAt(this.length - 1));
};
#2
Array对象的几个原型方法
Array.prototype.inArray = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
Array.prototype.max = function(){
for (var i = 1, max = this[0]; i < this.length; i++){
if (max < this[i]) {
max = this[i];
}
return max;
};
Array.prototype.min = function(){
for (var i = 1, min = this[0]; i < this.length; i++){
if (min > this[i]) {
min = this[i];
}
return min;
};
Array.prototype.inArray = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
Array.prototype.max = function(){
for (var i = 1, max = this[0]; i < this.length; i++){
if (max < this[i]) {
max = this[i];
}
return max;
};
Array.prototype.min = function(){
for (var i = 1, min = this[0]; i < this.length; i++){
if (min > this[i]) {
min = this[i];
}
return min;
};
#3
mark
#4
Date.prototype.format = function(format) //author: meizz
{
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 hh:mm:ss"));
{
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 hh:mm:ss"));
#5
String.prototype.endsWith = function(character){
return (character == this.charAt(this.length - 1));
};
String.prototype.startsWith = function(character){
return (character == this.charAt(0);
};
return (character == this.charAt(this.length - 1));
};
String.prototype.startsWith = function(character){
return (character == this.charAt(0);
};
#6
在这儿发现一个比较多的。
http://ttyp.cnblogs.com/archive/2004/10/26/56730.html
http://www.cnblogs.com/Files/ttyp/Js-Lib.rar
http://ttyp.cnblogs.com/archive/2004/10/26/56730.html
http://www.cnblogs.com/Files/ttyp/Js-Lib.rar
#7
Function.prototype.bind = function(o){
var self = this;
var arg = Array.prototype.slice.call(arguments,1);
return function(){
self.apply(self, arg );
}
}
var self = this;
var arg = Array.prototype.slice.call(arguments,1);
return function(){
self.apply(self, arg );
}
}
#8
关于日期的一些,原创
<script language="JavaScript">
<!--
/*用相对不规则的字符串来创建日期对象,不规则的含义为:顺序包含年月日三个数值串,有间隔*/
String.prototype.parseDate = function(){
var regThree = /^\D*(\d{2,4})\D+(\d{1,2})\D+(\d{1,2})\D*$/;
var regSix = /^\D*(\d{2,4})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D*$/;
//var str = "";
var date = null;
if(regThree.test(this))
date = new Date(this.replace(/\s/g,"").replace(regThree,"$1/$2/$3"));
else if(regSix.test(this)){
str = this.match(regSix);
date = new Date(str[1],str[2]-1,str[3],str[4],str[5],str[6]);
}else return new Date();
return date;
}
/*
* 功能:根据输入表达式返回日期字符串
* 参数:dateFmt:字符串,由以下结构组成
* yy:长写年,YY:短写年mm:数字月,MM:英文月,dd:日,hh:时,
* mi:分,ss秒,ms:毫秒,we:汉字星期,WE:英文星期.
* isFmtWithZero : 是否用0进行格式化,true or false
*/
Date.prototype.parseString = function(dateFmt,isFmtWithZero){
dateFmt = (dateFmt == null?"yy-mm-dd" : dateFmt);
isFmtWithZero = (isFmtWithZero == null?true : isFmtWithZero);
if(typeof(dateFmt) != "string" )
throw (new Error(-1, 'parseString()方法需要字符串类型参数!'));
var weekArr=[["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
["SUN","MON","TUR","WED","THU","FRI","SAT"]];
var monthArr=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var str=dateFmt;
var o = {
"yy" : this.getFullYear(),
"YY" : this.getYear(),
"mm" : this.getMonth()+1,
"MM" : monthArr[this.getMonth()],
"dd" : this.getDate(),
"hh" : this.getHours(),
"mi" : this.getMinutes(),
"ss" : this.getSeconds(),
"we" : weekArr[0][this.getDay()],
"WE" : weekArr[1][this.getDay()]
}
for(var i in o){
str = str.replace(new RegExp(i,"g"),o[i].toString().fmtWithZero(isFmtWithZero));
}
str = str.replace(/ms/g,this.getMilliseconds().toString().fmtWithZeroD(isFmtWithZero));
return str;
}
/*将一位数字格式化成两位,如: 9 to 09*/
String.prototype.fmtWithZero = function(isFmtWithZero){
return (isFmtWithZero && /^\d$/.test(this))?"0"+this:this;
}
String.prototype.fmtWithZeroD = function(isFmtWithZero){
return (isFmtWithZero && /^\d{2}$/.test(this))?"00"+this:((isFmtWithZero && /^\d$/.test(this))?"0"+this:this);
}
/* 功能 : 返回与某日期相距N天(N个24小时)的日期
* 参数 : num number类型 可以为正负整数或者浮点数,默认为1;
* type 0(秒) or 1(天),默认为天
* 返回 : 新的PowerDate类型
*/
Date.prototype.dateAfter=function(num,type){
num = (num == null?1:num);
if(typeof(num)!="number") throw new Error(-1,"dateAfterDays(num,type)的num参数为数值类型.");
type = (type==null?1:type);
var arr = [1000,86400000];
return new Date(this.valueOf() + num*arr[type]);
}
//判断是否是闰年,返回true 或者 false
Date.prototype.isLeapYear = function (){
var year = this.getFullYear();
return (0==year%4 && ((year % 100 != 0)||(year % 400 == 0)));
}
//返回该月天数
Date.prototype.getDaysOfMonth = function (){
return (new Date(this.getFullYear(),this.getMonth()+1,0)).getDate();
}
//日期比较函数,参数date:为Date类型,如this日期晚于参数:1,相等:0 早于: -1
Date.prototype.dateCompare = function(date){
if(typeof(date) != "object" || !(/Date/.test(date.constructor)))
throw new Error(-1,"dateCompare(date)的date参数为Date类型.");
var d = this.getTime() - date.getTime();
return d>0?1:(d==0?0:-1);
}
/*功能:返回两日期之差
*参数:pd PowerDate对象
* type: 返回类别标识.yy:年,mm:月,ww:周,dd:日,hh:小时,mi:分,ss:秒,ms:毫秒
* intOrFloat :返回整型还是浮点型值 0:整型,不等于0:浮点型
* output : 输出提示,如:时间差为#周!
*/
Date.prototype.calDateDistance = function (date,type,intOrFloat,output){
if(typeof(date) != "object" || !(/Date/.test(date.constructor)))
throw new Error(-1,"calDateDistance(date,type,intOrFloat)的date参数为Date类型.");
type = (type==null?'dd':type);
if(!((new RegExp(type+",","g")).test("yy,mm,ww,dd,hh,mi,ss,ms,")))
throw new Error(-1,"calDateDistance(pd,type,intOrFloat,output)的type参数为非法.");
var iof = (intOrFloat==null?0:intOrFloat);
var num=0;
var o = {
"ww" : 7*86400000,
"dd" : 86400000,
"hh" : 3600000,
"mi" : 60000,
"ss" : 1000,
"ms" : 1
}
switch(type){
case "yy": num = this.getFullYear() - date.getFullYear(); break;
case "mm": num = (this.getFullYear() - date.getFullYear())*12+this.getMonth()-date.getMonth(); break;
default:
var sub = this.valueOf() - date.valueOf();
if (o[type])
num = (sub/o[type]).fmtRtnVal(iof);
break;
}
return (output ? output.replace(/#/g," "+num+" ") : num);
}
//返回整数或者两位小数的浮点数
Number.prototype.fmtRtnVal = function (intOrFloat){
return (intOrFloat == 0 ? Math.floor(this) : parseInt(this*100)/100);
}
//根据当前日期所在年和周数返回周日的日期
Date.prototype.RtnByWeekNum = function (weekNum){
if(typeof(weekNum) != "number")
throw new Error(-1,"RtnByWeekNum(weekNum)的参数是数字类型.");
var date = new Date(this.getFullYear(),0,1);
var week = date.getDay();
week = (week==0?7:week);
return date.dateAfter(weekNum*7-week,1);
}
//根据日期返回该日期所在年的周数
Date.prototype.getWeekNum = function (){
var dat = new Date(this.getFullYear(),0,1);
var week = dat.getDay();
week = (week==0?7:week);
var days = this.calDateDistance(dat,"dd")+1;
return ((days + 6 - this.getDay() - 7 + week)/7);
}
//-->
</script>
<script language="JavaScript">
<!--
var date1 = "2005-11-1";
var date3 = "2006-1-10 11 11 11".parseDate();
var date2 = "2005-12-30".parseDate();
//alert(date3);
alert(date3.calDateDistance(date2,null,null,"时间差为#天!"));
//-->
</script>
<script language="JavaScript">
<!--
/*用相对不规则的字符串来创建日期对象,不规则的含义为:顺序包含年月日三个数值串,有间隔*/
String.prototype.parseDate = function(){
var regThree = /^\D*(\d{2,4})\D+(\d{1,2})\D+(\d{1,2})\D*$/;
var regSix = /^\D*(\d{2,4})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D*$/;
//var str = "";
var date = null;
if(regThree.test(this))
date = new Date(this.replace(/\s/g,"").replace(regThree,"$1/$2/$3"));
else if(regSix.test(this)){
str = this.match(regSix);
date = new Date(str[1],str[2]-1,str[3],str[4],str[5],str[6]);
}else return new Date();
return date;
}
/*
* 功能:根据输入表达式返回日期字符串
* 参数:dateFmt:字符串,由以下结构组成
* yy:长写年,YY:短写年mm:数字月,MM:英文月,dd:日,hh:时,
* mi:分,ss秒,ms:毫秒,we:汉字星期,WE:英文星期.
* isFmtWithZero : 是否用0进行格式化,true or false
*/
Date.prototype.parseString = function(dateFmt,isFmtWithZero){
dateFmt = (dateFmt == null?"yy-mm-dd" : dateFmt);
isFmtWithZero = (isFmtWithZero == null?true : isFmtWithZero);
if(typeof(dateFmt) != "string" )
throw (new Error(-1, 'parseString()方法需要字符串类型参数!'));
var weekArr=[["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
["SUN","MON","TUR","WED","THU","FRI","SAT"]];
var monthArr=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var str=dateFmt;
var o = {
"yy" : this.getFullYear(),
"YY" : this.getYear(),
"mm" : this.getMonth()+1,
"MM" : monthArr[this.getMonth()],
"dd" : this.getDate(),
"hh" : this.getHours(),
"mi" : this.getMinutes(),
"ss" : this.getSeconds(),
"we" : weekArr[0][this.getDay()],
"WE" : weekArr[1][this.getDay()]
}
for(var i in o){
str = str.replace(new RegExp(i,"g"),o[i].toString().fmtWithZero(isFmtWithZero));
}
str = str.replace(/ms/g,this.getMilliseconds().toString().fmtWithZeroD(isFmtWithZero));
return str;
}
/*将一位数字格式化成两位,如: 9 to 09*/
String.prototype.fmtWithZero = function(isFmtWithZero){
return (isFmtWithZero && /^\d$/.test(this))?"0"+this:this;
}
String.prototype.fmtWithZeroD = function(isFmtWithZero){
return (isFmtWithZero && /^\d{2}$/.test(this))?"00"+this:((isFmtWithZero && /^\d$/.test(this))?"0"+this:this);
}
/* 功能 : 返回与某日期相距N天(N个24小时)的日期
* 参数 : num number类型 可以为正负整数或者浮点数,默认为1;
* type 0(秒) or 1(天),默认为天
* 返回 : 新的PowerDate类型
*/
Date.prototype.dateAfter=function(num,type){
num = (num == null?1:num);
if(typeof(num)!="number") throw new Error(-1,"dateAfterDays(num,type)的num参数为数值类型.");
type = (type==null?1:type);
var arr = [1000,86400000];
return new Date(this.valueOf() + num*arr[type]);
}
//判断是否是闰年,返回true 或者 false
Date.prototype.isLeapYear = function (){
var year = this.getFullYear();
return (0==year%4 && ((year % 100 != 0)||(year % 400 == 0)));
}
//返回该月天数
Date.prototype.getDaysOfMonth = function (){
return (new Date(this.getFullYear(),this.getMonth()+1,0)).getDate();
}
//日期比较函数,参数date:为Date类型,如this日期晚于参数:1,相等:0 早于: -1
Date.prototype.dateCompare = function(date){
if(typeof(date) != "object" || !(/Date/.test(date.constructor)))
throw new Error(-1,"dateCompare(date)的date参数为Date类型.");
var d = this.getTime() - date.getTime();
return d>0?1:(d==0?0:-1);
}
/*功能:返回两日期之差
*参数:pd PowerDate对象
* type: 返回类别标识.yy:年,mm:月,ww:周,dd:日,hh:小时,mi:分,ss:秒,ms:毫秒
* intOrFloat :返回整型还是浮点型值 0:整型,不等于0:浮点型
* output : 输出提示,如:时间差为#周!
*/
Date.prototype.calDateDistance = function (date,type,intOrFloat,output){
if(typeof(date) != "object" || !(/Date/.test(date.constructor)))
throw new Error(-1,"calDateDistance(date,type,intOrFloat)的date参数为Date类型.");
type = (type==null?'dd':type);
if(!((new RegExp(type+",","g")).test("yy,mm,ww,dd,hh,mi,ss,ms,")))
throw new Error(-1,"calDateDistance(pd,type,intOrFloat,output)的type参数为非法.");
var iof = (intOrFloat==null?0:intOrFloat);
var num=0;
var o = {
"ww" : 7*86400000,
"dd" : 86400000,
"hh" : 3600000,
"mi" : 60000,
"ss" : 1000,
"ms" : 1
}
switch(type){
case "yy": num = this.getFullYear() - date.getFullYear(); break;
case "mm": num = (this.getFullYear() - date.getFullYear())*12+this.getMonth()-date.getMonth(); break;
default:
var sub = this.valueOf() - date.valueOf();
if (o[type])
num = (sub/o[type]).fmtRtnVal(iof);
break;
}
return (output ? output.replace(/#/g," "+num+" ") : num);
}
//返回整数或者两位小数的浮点数
Number.prototype.fmtRtnVal = function (intOrFloat){
return (intOrFloat == 0 ? Math.floor(this) : parseInt(this*100)/100);
}
//根据当前日期所在年和周数返回周日的日期
Date.prototype.RtnByWeekNum = function (weekNum){
if(typeof(weekNum) != "number")
throw new Error(-1,"RtnByWeekNum(weekNum)的参数是数字类型.");
var date = new Date(this.getFullYear(),0,1);
var week = date.getDay();
week = (week==0?7:week);
return date.dateAfter(weekNum*7-week,1);
}
//根据日期返回该日期所在年的周数
Date.prototype.getWeekNum = function (){
var dat = new Date(this.getFullYear(),0,1);
var week = dat.getDay();
week = (week==0?7:week);
var days = this.calDateDistance(dat,"dd")+1;
return ((days + 6 - this.getDay() - 7 + week)/7);
}
//-->
</script>
<script language="JavaScript">
<!--
var date1 = "2005-11-1";
var date3 = "2006-1-10 11 11 11".parseDate();
var date2 = "2005-12-30".parseDate();
//alert(date3);
alert(date3.calDateDistance(date2,null,null,"时间差为#天!"));
//-->
</script>
#9
学习..
#10
期待...
#11
String.prototype.cut = function(n){
var strTmp = "";
for(var i=0,l=this.length,k=0;(i<n);k++){
var ch = this.charAt(k);
if(ch.match(/[\x00-\x80]/)){
i += 1;
}
else{
i += 2;
}
strTmp += ch;
}
return strTmp;
}
截取定长字符串,一个汉字算两个字母宽..嘎嘎..得到的结果符还算整齐...
var strTmp = "";
for(var i=0,l=this.length,k=0;(i<n);k++){
var ch = this.charAt(k);
if(ch.match(/[\x00-\x80]/)){
i += 1;
}
else{
i += 2;
}
strTmp += ch;
}
return strTmp;
}
截取定长字符串,一个汉字算两个字母宽..嘎嘎..得到的结果符还算整齐...
#12
UP
#13
兄弟,打算整理了放哪里啊,一定要给我提个醒啊,上面的我先收了。
//--------------------------------------string-----------------------------------------
String.prototype.lTrim = function () {return this.replace(/^\s*/, "");}
String.prototype.rTrim = function () {return this.replace(/\s*$/, "");}
String.prototype.trim = function () {return this.rTrim().lTrim();}
String.prototype.endsWith = function(sEnd) {return (this.substr(this.length-sEnd.length)==sEnd);}
String.prototype.startsWith = function(sStart) {return (this.substr(0,sStart.length)==sStart);}
String.prototype.format = function()
{ var s = this; for (var i=0; i < arguments.length; i++)
{ s = s.replace("{" + (i) + "}", arguments[i]);}
return(s);}
String.prototype.removeSpaces = function()
{ return this.replace(/ /gi,'');}
String.prototype.removeExtraSpaces = function()
{ return(this.replace(String.prototype.removeExtraSpaces.re, " "));}
String.prototype.removeExtraSpaces.re = new RegExp("\\s+", "g");
String.prototype.removeSpaceDelimitedString = function(r)
{ var s = " " + this.trim() + " "; return s.replace(" " + r,"").rTrim();}
String.prototype.isEmpty = function() {return this.length==0;};
String.prototype.validateURL = function()
{ var urlRegX = /[^a-zA-Z0-9-]/g; return sURL.match(urlRegX, "");}
String.prototype.isEmail = function()
{ var emailReg = /^\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; return emailReg.test(this);}
String.prototype.isAlphaNumeric = function()
{ var alphaReg = /[^a-zA-Z0-9]/g; return !alphaReg.test(this);}
String.prototype.encodeURI = function()
{ var returnString; returnString = escape( this )
returnString = returnString.replace(/\+/g,"%2B"); return returnString
}
String.prototype.decodeURI = function() {return unescape(this)}
//--------------------------------------Array-----------------------------------------
Array.prototype.indexOf = function(p_var)
{
for (var i=0; i<this.length; i++)
{
if (this[i] == p_var)
{
return(i);
}
}
return(-1);
}
Array.prototype.exists = function(p_var) {return(this.indexOf(p_var) != -1);}
Array.prototype.queue = function(p_var) {this.push(p_var)}
Array.prototype.dequeue = function() {return(this.shift());}
Array.prototype.removeAt = function(p_iIndex) {return this.splice(p_iIndex, 1);}
Array.prototype.remove = function(o)
{
var i = this.indexOf(o); if (i>-1) this.splice(i,1); return (i>-1)
}
Array.prototype.clear = function()
{
var iLength = this.length;
for (var i=0; i < iLength; i++)
{
this.shift();
}
}
Array.prototype.addArray = function(p_a)
{
if (p_a)
{
for (var i=0; i < p_a.length; i++)
{
this.push(p_a[i]);
}
}
}
//--------------------------------------string-----------------------------------------
String.prototype.lTrim = function () {return this.replace(/^\s*/, "");}
String.prototype.rTrim = function () {return this.replace(/\s*$/, "");}
String.prototype.trim = function () {return this.rTrim().lTrim();}
String.prototype.endsWith = function(sEnd) {return (this.substr(this.length-sEnd.length)==sEnd);}
String.prototype.startsWith = function(sStart) {return (this.substr(0,sStart.length)==sStart);}
String.prototype.format = function()
{ var s = this; for (var i=0; i < arguments.length; i++)
{ s = s.replace("{" + (i) + "}", arguments[i]);}
return(s);}
String.prototype.removeSpaces = function()
{ return this.replace(/ /gi,'');}
String.prototype.removeExtraSpaces = function()
{ return(this.replace(String.prototype.removeExtraSpaces.re, " "));}
String.prototype.removeExtraSpaces.re = new RegExp("\\s+", "g");
String.prototype.removeSpaceDelimitedString = function(r)
{ var s = " " + this.trim() + " "; return s.replace(" " + r,"").rTrim();}
String.prototype.isEmpty = function() {return this.length==0;};
String.prototype.validateURL = function()
{ var urlRegX = /[^a-zA-Z0-9-]/g; return sURL.match(urlRegX, "");}
String.prototype.isEmail = function()
{ var emailReg = /^\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; return emailReg.test(this);}
String.prototype.isAlphaNumeric = function()
{ var alphaReg = /[^a-zA-Z0-9]/g; return !alphaReg.test(this);}
String.prototype.encodeURI = function()
{ var returnString; returnString = escape( this )
returnString = returnString.replace(/\+/g,"%2B"); return returnString
}
String.prototype.decodeURI = function() {return unescape(this)}
//--------------------------------------Array-----------------------------------------
Array.prototype.indexOf = function(p_var)
{
for (var i=0; i<this.length; i++)
{
if (this[i] == p_var)
{
return(i);
}
}
return(-1);
}
Array.prototype.exists = function(p_var) {return(this.indexOf(p_var) != -1);}
Array.prototype.queue = function(p_var) {this.push(p_var)}
Array.prototype.dequeue = function() {return(this.shift());}
Array.prototype.removeAt = function(p_iIndex) {return this.splice(p_iIndex, 1);}
Array.prototype.remove = function(o)
{
var i = this.indexOf(o); if (i>-1) this.splice(i,1); return (i>-1)
}
Array.prototype.clear = function()
{
var iLength = this.length;
for (var i=0; i < iLength; i++)
{
this.shift();
}
}
Array.prototype.addArray = function(p_a)
{
if (p_a)
{
for (var i=0; i < p_a.length; i++)
{
this.push(p_a[i]);
}
}
}
#14
楼上,一定通知你。
建议几点:
一、方法名最好模拟Java、.NET或VBScript的
如:
String.prototype.endsWith = function(){}; //Java和.NET中的String对象的endsWith方法。我建议不用endWith。
Object.prototype.isNumeric = function(){}; //VBScript中的IsNumeric方法
二、方法命名,因为是方法,所以遵守第一个单词字母小写,第二个大写。
这个String.prototype.trim = function(){};而不是Trim
Object.prototype.isNumeric = function() {};而不是IsNumeric
三、对已经有的方法,不封装,如
String对象已经有indexOf方法,就不必封装出一个inStr了。indexOf也很好用啊。
建议几点:
一、方法名最好模拟Java、.NET或VBScript的
如:
String.prototype.endsWith = function(){}; //Java和.NET中的String对象的endsWith方法。我建议不用endWith。
Object.prototype.isNumeric = function(){}; //VBScript中的IsNumeric方法
二、方法命名,因为是方法,所以遵守第一个单词字母小写,第二个大写。
这个String.prototype.trim = function(){};而不是Trim
Object.prototype.isNumeric = function() {};而不是IsNumeric
三、对已经有的方法,不封装,如
String对象已经有indexOf方法,就不必封装出一个inStr了。indexOf也很好用啊。
#15
也凑个热闹吧:
//排除数组重复项
Array.prototype.Unique = function()
{
var a = {}; for(var i=0; i<this.length; i++)
{
if(typeof a[this[i]] == "undefined")
a[this[i]] = 1;
}
this.length = 0;
for(var i in a)
this[this.length] = i;
return this;
};
//apply call
if(typeof(Function.prototype.apply)!="function")
{
Function.prototype.apply = function(obj, argu)
{
var s;
if(obj)
{
obj.constructor.prototype._caller=this;
s = "obj._caller";
}
else s = "this";
var a=[];
for(var i=0; i<argu.length; i++)
a[i] = "argu["+ i +"]";
return eval(s +"("+ a.join(",") +");");
};
Function.prototype.call = function(obj)
{
var a=[];
for(var i=1; i<arguments.length; i++)
a[i-1]=arguments[i];
return this.apply(obj, a);
};
}
if(typeof(Number.prototype.toFixed)!="function")
{
Number.prototype.toFixed = function(d)
{
var s=this+"";if(s.indexOf(".")==-1)s+=".";s+=new Array(d+1).join("0");
if (new RegExp("^((-|\\+)?\\d+(\\.\\d{0,"+ (d+1) +"})?)\\d*$").test(s))
{
s="0"+ RegExp.$1, pm=RegExp.$2, a=RegExp.$3.length, b=true;
if (a==d+2){a=s.match(/\d/g); if (parseInt(a[a.length-1])>4)
{
for(var i=a.length-2; i>=0; i--) {a[i] = parseInt(a[i])+1;
if(a[i]==10){a[i]=0; b=i!=1;} else break;}
}
s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");
}if(b)s=s.substr(1); return (pm+s).replace(/\.$/, "");} return this+"";
};
}
String.prototype.sub = function(n)
{
var r = /[^\x00-\xff]/g;
if(this.replace(r, "mm").length <= n) return this;
n = n - 3;
var m = Math.floor(n/2);
for(var i=m; i<this.length; i++)
{
if(this.substr(0, i).replace(r, "mm").length>=n)
{
return this.substr(0, i) +"...";
}
}
return this;
};
//排除数组重复项
Array.prototype.Unique = function()
{
var a = {}; for(var i=0; i<this.length; i++)
{
if(typeof a[this[i]] == "undefined")
a[this[i]] = 1;
}
this.length = 0;
for(var i in a)
this[this.length] = i;
return this;
};
//apply call
if(typeof(Function.prototype.apply)!="function")
{
Function.prototype.apply = function(obj, argu)
{
var s;
if(obj)
{
obj.constructor.prototype._caller=this;
s = "obj._caller";
}
else s = "this";
var a=[];
for(var i=0; i<argu.length; i++)
a[i] = "argu["+ i +"]";
return eval(s +"("+ a.join(",") +");");
};
Function.prototype.call = function(obj)
{
var a=[];
for(var i=1; i<arguments.length; i++)
a[i-1]=arguments[i];
return this.apply(obj, a);
};
}
if(typeof(Number.prototype.toFixed)!="function")
{
Number.prototype.toFixed = function(d)
{
var s=this+"";if(s.indexOf(".")==-1)s+=".";s+=new Array(d+1).join("0");
if (new RegExp("^((-|\\+)?\\d+(\\.\\d{0,"+ (d+1) +"})?)\\d*$").test(s))
{
s="0"+ RegExp.$1, pm=RegExp.$2, a=RegExp.$3.length, b=true;
if (a==d+2){a=s.match(/\d/g); if (parseInt(a[a.length-1])>4)
{
for(var i=a.length-2; i>=0; i--) {a[i] = parseInt(a[i])+1;
if(a[i]==10){a[i]=0; b=i!=1;} else break;}
}
s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");
}if(b)s=s.substr(1); return (pm+s).replace(/\.$/, "");} return this+"";
};
}
String.prototype.sub = function(n)
{
var r = /[^\x00-\xff]/g;
if(this.replace(r, "mm").length <= n) return this;
n = n - 3;
var m = Math.floor(n/2);
for(var i=m; i<this.length; i++)
{
if(this.substr(0, i).replace(r, "mm").length>=n)
{
return this.substr(0, i) +"...";
}
}
return this;
};
#16
meizz(梅花雪)来了,蓬筚生辉
#17
来玩
String.prototype.realLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
}
判断整型
String.prototype.isInteger = function()
{
//如果为空,则通过校验
if(this == "")
return true;
if(/^(\-?)(\d+)$/.test(this))
return true;
else
return false;
}
是否为空
String.prototype.isEmpty = function()
{
if(this.trim() == "")
return true;
else
return false;
}
String.prototype.realLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
}
判断整型
String.prototype.isInteger = function()
{
//如果为空,则通过校验
if(this == "")
return true;
if(/^(\-?)(\d+)$/.test(this))
return true;
else
return false;
}
是否为空
String.prototype.isEmpty = function()
{
if(this.trim() == "")
return true;
else
return false;
}
#18
hbhbhbhbhb1021(天外水火(我要多努力)) 版主多帖些,太少了,呵呵。
#19
学习
#20
工作日
Date.prototype.isWorkDay=function()
{
var year=this.getYear();
var month=this.getMonth();
var date=this.getDate();
var hour=this.getHours();
if(this.getDay()==6)
{
return false
}
if(this.getDay()==7)
{
return false
}
if((hour>7)&&(hour<17))
{
return true;
}
else
{
return false
}
}
var a=new Date();
alert(a.isWorkDay());
是否全为汉字
String.prototype.isAllChinese = function()
{
var pattern = /^([\u4E00-\u9FA5])*$/g;
if (pattern.test(this))
return true;
else
return false;
}
包含汉字
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}
全角转半角
<script language=javascript>
String.prototype.DBC2SBC=function()
{
var result = '';
for(var i=0;i<str.length;i++){
code = str.charCodeAt(i);//获取当前字符的unicode编码
if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
{
result += String.fromCharCode(str.charCodeAt(i) - 65248);//把全角字符的unicode编码转换为对应半角字符的unicode码
}else if (code == 12288)//空格
{
result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
}else
{
result += str.charAt(i);
}
}
return result;
}
var str="FSDFSDG广泛豆腐干"
alert(str)
alert(str.DBC2SBC())
</script>
Date.prototype.isWorkDay=function()
{
var year=this.getYear();
var month=this.getMonth();
var date=this.getDate();
var hour=this.getHours();
if(this.getDay()==6)
{
return false
}
if(this.getDay()==7)
{
return false
}
if((hour>7)&&(hour<17))
{
return true;
}
else
{
return false
}
}
var a=new Date();
alert(a.isWorkDay());
是否全为汉字
String.prototype.isAllChinese = function()
{
var pattern = /^([\u4E00-\u9FA5])*$/g;
if (pattern.test(this))
return true;
else
return false;
}
包含汉字
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}
全角转半角
<script language=javascript>
String.prototype.DBC2SBC=function()
{
var result = '';
for(var i=0;i<str.length;i++){
code = str.charCodeAt(i);//获取当前字符的unicode编码
if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
{
result += String.fromCharCode(str.charCodeAt(i) - 65248);//把全角字符的unicode编码转换为对应半角字符的unicode码
}else if (code == 12288)//空格
{
result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
}else
{
result += str.charAt(i);
}
}
return result;
}
var str="FSDFSDG广泛豆腐干"
alert(str)
alert(str.DBC2SBC())
</script>
#21
嘿嘿,大家都来给KimSoft(革命的小酒天天醉) 捧场啊
#22
强啊,学习!
#23
优化一下代码:
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}
==>
String.prototype.isContainChinese = function()
{
return /[\u4e00-\u9fa5\uf900-\ufa2d]/.test(this);
}
其它的类推优化
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}
==>
String.prototype.isContainChinese = function()
{
return /[\u4e00-\u9fa5\uf900-\ufa2d]/.test(this);
}
其它的类推优化
#24
支持,学习 ^_^
#25
的确,我的代码多用到变量
就拿这里来讲,这里有两句return true; return false;
我想这里就需要有两个对象来存储,浪费了资源。
而meizz的不管返回true或者false都应该存储在一个对象里。
TO meizz
除了这点之外,写成那种还有其他原因吗?
就拿这里来讲,这里有两句return true; return false;
我想这里就需要有两个对象来存储,浪费了资源。
而meizz的不管返回true或者false都应该存储在一个对象里。
TO meizz
除了这点之外,写成那种还有其他原因吗?
#26
减少消耗(少用了变量)
提高效率(少了if判断)
代码精简
提高效率(少了if判断)
代码精简
#27
楼上两位再帮我看看这个帖子。。。
http://community.csdn.net/Expert/topic/4609/4609496.xml?temp=.1486322
http://community.csdn.net/Expert/topic/4609/4609496.xml?temp=.1486322
#28
还有就是不要在正则里动不动就添加 g 模式:
/^([\u4E00-\u9FA5])*$/g //String.prototype.isAllChinese
这句正则里的 g 模式若是配合以 m 模式那还说得过去,你即然没有 m 那何必要添个 g ?
还有你用的是 * 若这一个空字符串你也认为是 isAllChinese ?所以应该用+
/^[\u4e00-\u9fa5\uf900-\ufa2d]+$/
var pattern = /[\u4E00-\u9FA5]/g; //String.prototype.isContainChinese
这句正则里加了一个无用的 g ,对系统消耗则相差甚大呀
/^([\u4E00-\u9FA5])*$/g //String.prototype.isAllChinese
这句正则里的 g 模式若是配合以 m 模式那还说得过去,你即然没有 m 那何必要添个 g ?
还有你用的是 * 若这一个空字符串你也认为是 isAllChinese ?所以应该用+
/^[\u4e00-\u9fa5\uf900-\ufa2d]+$/
var pattern = /[\u4E00-\u9FA5]/g; //String.prototype.isContainChinese
这句正则里加了一个无用的 g ,对系统消耗则相差甚大呀
#29
TO meizz(梅花雪)
灯泡(这个是帖图),以后我写代码要多注意了。
灯泡(这个是帖图),以后我写代码要多注意了。
#30
一看正则式就头大。一直将这个章节跳过去的,不知有没好的学习方法。
#31
呵呵,被挖走了
正则用处可大了,有时候能起到事半功倍的效果,.net里的正则比JS的还复杂
正则用处可大了,有时候能起到事半功倍的效果,.net里的正则比JS的还复杂
#32
先收藏下
#33
佩服各位高手的JS功力,象你们学习
#34
顶
#35
http://bbs.51js.com/viewthread.php?tid=1666
里面有一些可以整理下
里面有一些可以整理下
#36
公司光纤断了...偶正好出来办个事,偷空上个网.
#37
这个应该置顶
#38
up ^_^
#39
/******************************************************************************
* Array
******************************************************************************/
/* 返回数组中最大值 */
Array.prototype.max = function()
{
var i, max = this[0];
for (i = 1; i < this.length; i++)
{
if (max < this[i])
{
max = this[i];
}
}
return max;
};
/* 兼容ie5.0 */
if (!Array.prototype.push)
{
Array.prototype.push = function()
{
var startLength = this.length;
for (var i = 0; i < arguments.length; i++)
{
this[startLength + i] = arguments;
}
return this.length;
};
}
/* 返回 Array 对象内第一次出现 给定值 的索引值 */
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = 0;
}
else if (fromIndex < 0)
{
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex; i < this.length; i++)
{
if (this[i] === obj)
{
return i;
}
}
return-1;
};
}
/* 返回 Array 对象内最后一次出现 给定值 的索引值 */
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = this.length - 1;
}
else if (fromIndex < 0)
{
fromIndex=Math.max(0, this.length+fromIndex);
}
for (var i = fromIndex; i >= 0; i--)
{
if (this[i] === obj)
{
return i;
}
}
return -1;
};
}
/* Array.insert(值, 索引) */
Array.prototype.insertAt = function(o, i)
{
this.splice(i, 0, o);
};
/* Array.insertBefore(插入值, 值) */
Array.prototype.insertBefore = function(o, o2)
{
var i = this.indexOf(o2);
if (i == -1)
{
this.push(o);
}
else
{
this.splice(i, 0, o);
}
};
/* 删除给定元素 */
Array.prototype.remove = function(o)
{
var i = this.indexOf(o);
if (i != -1)
{
this.splice(i, 1);
}
};
/* 删除给定索引值位置的元素 */
Array.prototype.removeAt = function(i)
{
this.splice(i, 1);
};
/* 判断是否存在给定值 */
Array.prototype.contains = function(o)
{
return this.indexOf(o) != -1
};
/* 随机排序 */
Array.prototype.random = function ()
{
return this.sort(function(){return Math.random()*new Date%3-1})
};
/* 是否包含给定数组 */
Array.prototype.compare = function (a)
{
return this.toString().match(new RegExp("("+a.join("|")+")", "g"))
};
/* 复制数组 */
Array.prototype.copy = function(o)
{
return this.concat();
};
/* */
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
f.call(obj, this[i], i, this);
}
};
}
/* */
if (!Array.prototype.filter)
{
Array.prototype.filter = function(f, obj)
{
var l = this.length;
var res = [];
for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
res.push(this[i]);
}
}
return res;
};
}
/* */
if (!Array.prototype.map)
{
Array.prototype.map = function(f, obj)
{
var l = this.length;
var res = [];
for (var i = 0; i < l; i++)
{
res.push(f.call(obj, this[i], i, this));
}
return res;
};
}
/* */
if (!Array.prototype.some)
{
Array.prototype.some = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
return true;
}
}
return false;
};
}
/* */
if (!Array.prototype.every)
{
Array.prototype.every = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
if (!f.call(obj, this[i], i, this))
{
return false;
}
}
return true;
};
}
/******************************************************************************
* Date
******************************************************************************/
/* 格式化日期yyyy-MM-dd-mm-ss-q-S */
Date.prototype.Format = function(format)
{
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(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;
};
/* 是否周末 */
Date.prototype.isWeekend = function()
{
return (this.getDay() % 6) ? false : true;
};
/* 该月总共天数 */
Date.prototype.getMDate = function()
{
return (new Date(this.getFullYear(), this.getMonth()+1, 0).getDate())
};
/******************************************************************************
* Math
******************************************************************************/
/* Math.random()的重载函数 ; Math.random(n),返回小于n的整数 ; */
var _rnd = Math.random;
Math.random = function(n)
{
if (n == undefined)
{
return _rnd();
}
else if (n.toString().match(/^\-?\d*$/g))
{
return Math.round(_rnd()*n);
}
else
{
return null;
}
};
/******************************************************************************
* Number
******************************************************************************/
/* 返回数值的长度 */
Number.prototype.length = function()
{
return this.toString().length;
};
/* 将整数形式RGB颜色值转换为HEX形式 */
Number.prototype.toColorPart = function()
{
var digits = this.toString(16);
if (this < 16)
{
return '0' + digits;
}
return digits;
};
/* 返回000888形式 */
Number.prototype.format = function(n)
{
if (this.length() >= n)
{
return this;
}
return ((new Array(n).join("0")+(this|0)).slice(-n));
};
/******************************************************************************
* String
******************************************************************************/
/* 去掉字符串左端空格 */
String.prototype.lTrim = function()
{
return this.replace(/^\s*/, "");
};
/* 去掉字符串右端空格 */
String.prototype.rTrim = function()
{
return this.replace(/\s*$/, "");
};
/* 去掉字符串两端空格 */
String.prototype.Trim = function()
{
return this.replace(/^\s*|\s*$/g, "");
};
/* 返回字符串字节数 */
String.prototype.getBytesLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
};
/* 字符串首字母大写 */
String.prototype.capitalize = function()
{
return this.charAt(0).toUpperCase()+this.substr(1);
};
* Array
******************************************************************************/
/* 返回数组中最大值 */
Array.prototype.max = function()
{
var i, max = this[0];
for (i = 1; i < this.length; i++)
{
if (max < this[i])
{
max = this[i];
}
}
return max;
};
/* 兼容ie5.0 */
if (!Array.prototype.push)
{
Array.prototype.push = function()
{
var startLength = this.length;
for (var i = 0; i < arguments.length; i++)
{
this[startLength + i] = arguments;
}
return this.length;
};
}
/* 返回 Array 对象内第一次出现 给定值 的索引值 */
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = 0;
}
else if (fromIndex < 0)
{
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex; i < this.length; i++)
{
if (this[i] === obj)
{
return i;
}
}
return-1;
};
}
/* 返回 Array 对象内最后一次出现 给定值 的索引值 */
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = this.length - 1;
}
else if (fromIndex < 0)
{
fromIndex=Math.max(0, this.length+fromIndex);
}
for (var i = fromIndex; i >= 0; i--)
{
if (this[i] === obj)
{
return i;
}
}
return -1;
};
}
/* Array.insert(值, 索引) */
Array.prototype.insertAt = function(o, i)
{
this.splice(i, 0, o);
};
/* Array.insertBefore(插入值, 值) */
Array.prototype.insertBefore = function(o, o2)
{
var i = this.indexOf(o2);
if (i == -1)
{
this.push(o);
}
else
{
this.splice(i, 0, o);
}
};
/* 删除给定元素 */
Array.prototype.remove = function(o)
{
var i = this.indexOf(o);
if (i != -1)
{
this.splice(i, 1);
}
};
/* 删除给定索引值位置的元素 */
Array.prototype.removeAt = function(i)
{
this.splice(i, 1);
};
/* 判断是否存在给定值 */
Array.prototype.contains = function(o)
{
return this.indexOf(o) != -1
};
/* 随机排序 */
Array.prototype.random = function ()
{
return this.sort(function(){return Math.random()*new Date%3-1})
};
/* 是否包含给定数组 */
Array.prototype.compare = function (a)
{
return this.toString().match(new RegExp("("+a.join("|")+")", "g"))
};
/* 复制数组 */
Array.prototype.copy = function(o)
{
return this.concat();
};
/* */
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
f.call(obj, this[i], i, this);
}
};
}
/* */
if (!Array.prototype.filter)
{
Array.prototype.filter = function(f, obj)
{
var l = this.length;
var res = [];
for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
res.push(this[i]);
}
}
return res;
};
}
/* */
if (!Array.prototype.map)
{
Array.prototype.map = function(f, obj)
{
var l = this.length;
var res = [];
for (var i = 0; i < l; i++)
{
res.push(f.call(obj, this[i], i, this));
}
return res;
};
}
/* */
if (!Array.prototype.some)
{
Array.prototype.some = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
return true;
}
}
return false;
};
}
/* */
if (!Array.prototype.every)
{
Array.prototype.every = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
if (!f.call(obj, this[i], i, this))
{
return false;
}
}
return true;
};
}
/******************************************************************************
* Date
******************************************************************************/
/* 格式化日期yyyy-MM-dd-mm-ss-q-S */
Date.prototype.Format = function(format)
{
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(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;
};
/* 是否周末 */
Date.prototype.isWeekend = function()
{
return (this.getDay() % 6) ? false : true;
};
/* 该月总共天数 */
Date.prototype.getMDate = function()
{
return (new Date(this.getFullYear(), this.getMonth()+1, 0).getDate())
};
/******************************************************************************
* Math
******************************************************************************/
/* Math.random()的重载函数 ; Math.random(n),返回小于n的整数 ; */
var _rnd = Math.random;
Math.random = function(n)
{
if (n == undefined)
{
return _rnd();
}
else if (n.toString().match(/^\-?\d*$/g))
{
return Math.round(_rnd()*n);
}
else
{
return null;
}
};
/******************************************************************************
* Number
******************************************************************************/
/* 返回数值的长度 */
Number.prototype.length = function()
{
return this.toString().length;
};
/* 将整数形式RGB颜色值转换为HEX形式 */
Number.prototype.toColorPart = function()
{
var digits = this.toString(16);
if (this < 16)
{
return '0' + digits;
}
return digits;
};
/* 返回000888形式 */
Number.prototype.format = function(n)
{
if (this.length() >= n)
{
return this;
}
return ((new Array(n).join("0")+(this|0)).slice(-n));
};
/******************************************************************************
* String
******************************************************************************/
/* 去掉字符串左端空格 */
String.prototype.lTrim = function()
{
return this.replace(/^\s*/, "");
};
/* 去掉字符串右端空格 */
String.prototype.rTrim = function()
{
return this.replace(/\s*$/, "");
};
/* 去掉字符串两端空格 */
String.prototype.Trim = function()
{
return this.replace(/^\s*|\s*$/g, "");
};
/* 返回字符串字节数 */
String.prototype.getBytesLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
};
/* 字符串首字母大写 */
String.prototype.capitalize = function()
{
return this.charAt(0).toUpperCase()+this.substr(1);
};
#40
/* Function.call & applay 兼容ie5 参考prototype.js */
if (!Function.prototype.apply)
{
Function.prototype.apply = function(object, argu)
{
if (!object)
{
object = window;
}
if (!argu)
{
argu = new Array();
}
object.__apply__ = this;
var result = eval("object.__apply__(" + argu.join(", ") + ")");
object.__apply__ = null;
return result;
};
Function.prototype.call = function(object)
{
var argu = new Array();
for (var i = 1; i < arguments.length; i++)
{
argu[i-1] = arguments[i];
}
return this.apply(object, argu)
};
}
/* 为类蹭加set & get 方法, 参考bindows */
Function.READ = 1;
Function.WRITE = 2;
Function.READ_WRITE = 3;
Function.prototype.addProperty = function(sName, nReadWrite)
{
nReadWrite = nReadWrite || Function.READ_WRITE;
var capitalized = sName.charAt(0).toUpperCase() + sName.substr(1);
if (nReadWrite & Function.READ)
{
this.prototype["get"+capitalized] = new Function("","return this._" + sName + ";");
}
if (nReadWrite & Function.WRITE)
{
this.prototype["set"+capitalized] = new Function(sName,"this._" + sName + " = " + sName + ";");
}
};
/* 类继承, 参考bindows继承实现方式 */
Function.prototype.Extend = function(parentFunc, className)
{
var _parentFunc = parentFunc;
var p = this.prototype = new _parentFunc();
p.constructor = this;
if (className)
{
p._className = className;
}
else
{
p._className = "Object";
}
p.toString = function()
{
return "[object " + this._className + "]";
};
return p;
};
/* 实体化类 */
Function.prototype.Create = function()
{
return new this;
};
if (!Function.prototype.apply)
{
Function.prototype.apply = function(object, argu)
{
if (!object)
{
object = window;
}
if (!argu)
{
argu = new Array();
}
object.__apply__ = this;
var result = eval("object.__apply__(" + argu.join(", ") + ")");
object.__apply__ = null;
return result;
};
Function.prototype.call = function(object)
{
var argu = new Array();
for (var i = 1; i < arguments.length; i++)
{
argu[i-1] = arguments[i];
}
return this.apply(object, argu)
};
}
/* 为类蹭加set & get 方法, 参考bindows */
Function.READ = 1;
Function.WRITE = 2;
Function.READ_WRITE = 3;
Function.prototype.addProperty = function(sName, nReadWrite)
{
nReadWrite = nReadWrite || Function.READ_WRITE;
var capitalized = sName.charAt(0).toUpperCase() + sName.substr(1);
if (nReadWrite & Function.READ)
{
this.prototype["get"+capitalized] = new Function("","return this._" + sName + ";");
}
if (nReadWrite & Function.WRITE)
{
this.prototype["set"+capitalized] = new Function(sName,"this._" + sName + " = " + sName + ";");
}
};
/* 类继承, 参考bindows继承实现方式 */
Function.prototype.Extend = function(parentFunc, className)
{
var _parentFunc = parentFunc;
var p = this.prototype = new _parentFunc();
p.constructor = this;
if (className)
{
p._className = className;
}
else
{
p._className = "Object";
}
p.toString = function()
{
return "[object " + this._className + "]";
};
return p;
};
/* 实体化类 */
Function.prototype.Create = function()
{
return new this;
};
#41
mozilla 下没有的方法和属性~~
if (mozilla)
{
//////////////////////////////////////////////////////////////
/* HTMLObject.outerHTML || HTMLObject.innerText */
HTMLElement.prototype.__defineGetter__
(
"outerHTML",
function()
{
var str = "<" + this.tagName;
for (var i = 0; i < this.attributes.length; i++)
{
var attr = this.attributes[i];
str += " ";
str += attr.nodeName + "=" + '"' + attr.nodeValue + '"';
}
str += ">" + this.innerHTML + "</" + this.tagName + ">";
return str;
}
);
HTMLElement.prototype.__defineGetter__
(
"innerText",
function()
{
var rng = document.createRange();
rng.selectNode(this);
return rng.toString();
}
);
HTMLElement.prototype.__defineSetter__
(
"innerText",
function(txt)
{
var rng = document.createRange();
rng.selectNodeContents(this);
rng.deleteContents();
var newText = document.createTextNode(txt);
this.appendChild(newText);
}
);
/* event.srcElement || event.target */
Event.prototype.__defineGetter__
(
"srcElement",
function()
{
return this.target;
}
);
/* Object.attachEvent || Object.addEventListener
Object.detachEvent || Object.removeEventListener */
HTMLElement.prototype.attachEvent = Node.prototype.attachEvent = function(a, b)
{
return this.addEventListener(a.replace(/^on/i, ""), b,false);
};
HTMLElement.prototype.detachEvent = Node.prototype.detachEvent = function(a, b)
{
return this.removeEventListener(a.replace(/^on/i, ""), b, false);
};
/* XMLDocument.onreadystatechange, parseError
XMLDocument.createNode, load, loadXML,setProperty */
var _xmlDocPrototype = XMLDocument.prototype;
XMLDocument.prototype.__defineSetter__
(
"onreadystatechange",
function(f)
{
if (this._onreadystatechange)
{
this.removeEventListener("load", this._onreadystatechange, false);
}
this._onreadystatechange = f;
if (f)
{
this.addEventListener("load", f, false);
}
return f;
}
);
XMLDocument.prototype.createNode = function(aType, aName, aNamespace)
{
switch(aType)
{
case 1:
if (aNamespace && aNamespace != "")
{
return this.createElementNS(aNamespace, aName);
}
else
{
return this.createElement(aName);
}
case 2:
if (aNamespace && aNamespace != "")
{
return this.createAttributeNS(aNamespace,aName);
}
else
{
return this.createAttribute(aName);
}
case 3:
default:
return this.createTextNode("");
}
};
XMLDocument.prototype.__realLoad = _xmlDocPrototype.load;
XMLDocument.prototype.load = function(sUri)
{
this.readyState = 0;
this.__realLoad(sUri);
};
XMLDocument.prototype.loadXML = function(s)
{
var doc2 = (new DOMParser).parseFromString(s, "text/xml");
while (this.hasChildNodes())
{
this.removeChild(this.lastChild);
}
var cs=doc2.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++)
{
this.appendChild(this.importNode(cs[i], true));
}
};
XMLDocument.prototype.setProperty = function(sName, sValue)
{
if (sName == "SelectionNamespaces")
{
this._selectionNamespaces = {};
var parts = sValue.split(/\s+/);
var re= /^xmlns\:([^=]+)\=((\"([^\"]*)\")|(\'([^\']*)\'))$/;
for (var i = 0; i < parts.length; i++)
{
re.test(parts[i]);
this._selectionNamespaces[RegExp.$1] = RegExp.$4 || RegExp.$6;
}
}
};
var _mozHasParseError = function(oDoc)
{
return !oDoc.documentElement || oDoc.documentElement.localName=="parsererror"
&& oDoc.documentElement.getAttribute("xmlns")=="http://www.mozilla.org/newlayout/xml/parsererror.xml";
};
XMLDocument.prototype.__defineGetter__
(
"parseError",
function()
{
var hasError = _mozHasParseError(this);
var res = {
errorCode : 0,
filepos : 0,
line : 0,
linepos : 0,
reason : "",
srcText : "",
url : ""
};
if (hasError)
{
res.errorCode = -1;
try
{
res.srcText = this.getElementsByTagName("sourcetext")[0].firstChild.data;
res.srcText = res.srcText.replace(/\n\-\^$/, "");
}
catch(ex)
{
res.srcText = "";
}
try
{
var s = this.documentElement.firstChild.data;
var re = /XML Parsing Error\:(.+)\nLocation\:(.+)\nLine Number(\d+)\,Column(\d+)/;
var a = re.exec(s);
res.reason = a[1];
res.url = a[2];
res.line = a[3];
res.linepos = a[4];
}
catch(ex)
{
res.reason="Unknown";
}
}
return res;
}
);
/* Attr.xml */
Attr.prototype.__defineGetter__
(
"xml",
function()
{
var nv = (new XMLSerializer).serializeToString(this);
return this.nodeName + "=\""+nv.replace(/\"/g,""")+"\"";
}
);
/* Node.xml, text, baseName
Node.selectNodes, selectSingleNode, transformNode, transformNodeToObject */
Node.prototype.__defineGetter__
(
"xml",
function()
{
return (new XMLSerializer).serializeToString(this);
}
);
Node.prototype.__defineGetter__
(
"text",
function()
{
var cs = this.childNodes;
var l = cs.length;
var sb = new Array(l);
for (var i = 0; i < l; i++)
{
sb[i] = cs[i].text.replace(/^\n/, "");
}
return sb.join("");
}
);
Node.prototype.__defineGetter__
(
"baseName",
function()
{
var lParts = this.nodeName.split(":");
return lParts[lParts.length-1];
}
);
Node.prototype.selectNodes = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;
if (doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if (s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}
return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}
var xpRes = doc.evaluate(sExpr, this, nsRes2, 5, null);
var res=[];
var item;
while ((item = xpRes.iterateNext()))
res.push(item);
return res;
};
Node.prototype.selectSingleNode = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;
if(doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if(s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}
return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}
var xpRes = doc.evaluate(sExpr, this, nsRes2, 9, null);
return xpRes.singleNodeValue;
};
Node.prototype.transformNode = function(oXsltNode)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var processor = new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df = processor.transformToFragment(this, doc);
return df.xml;
};
Node.prototype.transformNodeToObject = function(oXsltNode, oOutputDocument)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var outDoc = oOutputDocument.nodeType==9 ? oOutputDocument : oOutputDocument.ownerDocument;
var processor=new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df=processor.transformToFragment(this,doc);
while (oOutputDocument.hasChildNodes())
{
oOutputDocument.removeChild(oOutputDocument.lastChild);
}
var cs=df.childNodes;
var l=cs.length;
for(var i=0; i<l; i++)
{
oOutputDocument.appendChild(outDoc.importNode(cs[i],true));
}
};
/* TextNode.text */
Text.prototype.__defineGetter__
(
"text",
function()
{
return this.nodeValue;
}
);
//////////////////////////////////////////////////////////////
}
if (mozilla)
{
//////////////////////////////////////////////////////////////
/* HTMLObject.outerHTML || HTMLObject.innerText */
HTMLElement.prototype.__defineGetter__
(
"outerHTML",
function()
{
var str = "<" + this.tagName;
for (var i = 0; i < this.attributes.length; i++)
{
var attr = this.attributes[i];
str += " ";
str += attr.nodeName + "=" + '"' + attr.nodeValue + '"';
}
str += ">" + this.innerHTML + "</" + this.tagName + ">";
return str;
}
);
HTMLElement.prototype.__defineGetter__
(
"innerText",
function()
{
var rng = document.createRange();
rng.selectNode(this);
return rng.toString();
}
);
HTMLElement.prototype.__defineSetter__
(
"innerText",
function(txt)
{
var rng = document.createRange();
rng.selectNodeContents(this);
rng.deleteContents();
var newText = document.createTextNode(txt);
this.appendChild(newText);
}
);
/* event.srcElement || event.target */
Event.prototype.__defineGetter__
(
"srcElement",
function()
{
return this.target;
}
);
/* Object.attachEvent || Object.addEventListener
Object.detachEvent || Object.removeEventListener */
HTMLElement.prototype.attachEvent = Node.prototype.attachEvent = function(a, b)
{
return this.addEventListener(a.replace(/^on/i, ""), b,false);
};
HTMLElement.prototype.detachEvent = Node.prototype.detachEvent = function(a, b)
{
return this.removeEventListener(a.replace(/^on/i, ""), b, false);
};
/* XMLDocument.onreadystatechange, parseError
XMLDocument.createNode, load, loadXML,setProperty */
var _xmlDocPrototype = XMLDocument.prototype;
XMLDocument.prototype.__defineSetter__
(
"onreadystatechange",
function(f)
{
if (this._onreadystatechange)
{
this.removeEventListener("load", this._onreadystatechange, false);
}
this._onreadystatechange = f;
if (f)
{
this.addEventListener("load", f, false);
}
return f;
}
);
XMLDocument.prototype.createNode = function(aType, aName, aNamespace)
{
switch(aType)
{
case 1:
if (aNamespace && aNamespace != "")
{
return this.createElementNS(aNamespace, aName);
}
else
{
return this.createElement(aName);
}
case 2:
if (aNamespace && aNamespace != "")
{
return this.createAttributeNS(aNamespace,aName);
}
else
{
return this.createAttribute(aName);
}
case 3:
default:
return this.createTextNode("");
}
};
XMLDocument.prototype.__realLoad = _xmlDocPrototype.load;
XMLDocument.prototype.load = function(sUri)
{
this.readyState = 0;
this.__realLoad(sUri);
};
XMLDocument.prototype.loadXML = function(s)
{
var doc2 = (new DOMParser).parseFromString(s, "text/xml");
while (this.hasChildNodes())
{
this.removeChild(this.lastChild);
}
var cs=doc2.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++)
{
this.appendChild(this.importNode(cs[i], true));
}
};
XMLDocument.prototype.setProperty = function(sName, sValue)
{
if (sName == "SelectionNamespaces")
{
this._selectionNamespaces = {};
var parts = sValue.split(/\s+/);
var re= /^xmlns\:([^=]+)\=((\"([^\"]*)\")|(\'([^\']*)\'))$/;
for (var i = 0; i < parts.length; i++)
{
re.test(parts[i]);
this._selectionNamespaces[RegExp.$1] = RegExp.$4 || RegExp.$6;
}
}
};
var _mozHasParseError = function(oDoc)
{
return !oDoc.documentElement || oDoc.documentElement.localName=="parsererror"
&& oDoc.documentElement.getAttribute("xmlns")=="http://www.mozilla.org/newlayout/xml/parsererror.xml";
};
XMLDocument.prototype.__defineGetter__
(
"parseError",
function()
{
var hasError = _mozHasParseError(this);
var res = {
errorCode : 0,
filepos : 0,
line : 0,
linepos : 0,
reason : "",
srcText : "",
url : ""
};
if (hasError)
{
res.errorCode = -1;
try
{
res.srcText = this.getElementsByTagName("sourcetext")[0].firstChild.data;
res.srcText = res.srcText.replace(/\n\-\^$/, "");
}
catch(ex)
{
res.srcText = "";
}
try
{
var s = this.documentElement.firstChild.data;
var re = /XML Parsing Error\:(.+)\nLocation\:(.+)\nLine Number(\d+)\,Column(\d+)/;
var a = re.exec(s);
res.reason = a[1];
res.url = a[2];
res.line = a[3];
res.linepos = a[4];
}
catch(ex)
{
res.reason="Unknown";
}
}
return res;
}
);
/* Attr.xml */
Attr.prototype.__defineGetter__
(
"xml",
function()
{
var nv = (new XMLSerializer).serializeToString(this);
return this.nodeName + "=\""+nv.replace(/\"/g,""")+"\"";
}
);
/* Node.xml, text, baseName
Node.selectNodes, selectSingleNode, transformNode, transformNodeToObject */
Node.prototype.__defineGetter__
(
"xml",
function()
{
return (new XMLSerializer).serializeToString(this);
}
);
Node.prototype.__defineGetter__
(
"text",
function()
{
var cs = this.childNodes;
var l = cs.length;
var sb = new Array(l);
for (var i = 0; i < l; i++)
{
sb[i] = cs[i].text.replace(/^\n/, "");
}
return sb.join("");
}
);
Node.prototype.__defineGetter__
(
"baseName",
function()
{
var lParts = this.nodeName.split(":");
return lParts[lParts.length-1];
}
);
Node.prototype.selectNodes = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;
if (doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if (s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}
return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}
var xpRes = doc.evaluate(sExpr, this, nsRes2, 5, null);
var res=[];
var item;
while ((item = xpRes.iterateNext()))
res.push(item);
return res;
};
Node.prototype.selectSingleNode = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;
if(doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if(s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}
return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}
var xpRes = doc.evaluate(sExpr, this, nsRes2, 9, null);
return xpRes.singleNodeValue;
};
Node.prototype.transformNode = function(oXsltNode)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var processor = new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df = processor.transformToFragment(this, doc);
return df.xml;
};
Node.prototype.transformNodeToObject = function(oXsltNode, oOutputDocument)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var outDoc = oOutputDocument.nodeType==9 ? oOutputDocument : oOutputDocument.ownerDocument;
var processor=new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df=processor.transformToFragment(this,doc);
while (oOutputDocument.hasChildNodes())
{
oOutputDocument.removeChild(oOutputDocument.lastChild);
}
var cs=df.childNodes;
var l=cs.length;
for(var i=0; i<l; i++)
{
oOutputDocument.appendChild(outDoc.importNode(cs[i],true));
}
};
/* TextNode.text */
Text.prototype.__defineGetter__
(
"text",
function()
{
return this.nodeValue;
}
);
//////////////////////////////////////////////////////////////
}
#42
好多啊,谢谢楼上支持。
#1
自己先顶:
String对象的几个原型方法:
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
};
String.prototype.ltrim = function(){
return this.replace(/(^\s*)/g, "");
};
String.prototype.rtrim = function(){
return this.replace(/(\s*$)/g, "");
};
//取字符串第一个字符的 Unicode 编码
String.prototype.ascii = function(){
return this.charCodeAt(0);
};
String.prototype.endsWith = function(character){
return (character == this.charAt(this.length - 1));
};
String对象的几个原型方法:
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
};
String.prototype.ltrim = function(){
return this.replace(/(^\s*)/g, "");
};
String.prototype.rtrim = function(){
return this.replace(/(\s*$)/g, "");
};
//取字符串第一个字符的 Unicode 编码
String.prototype.ascii = function(){
return this.charCodeAt(0);
};
String.prototype.endsWith = function(character){
return (character == this.charAt(this.length - 1));
};
#2
Array对象的几个原型方法
Array.prototype.inArray = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
Array.prototype.max = function(){
for (var i = 1, max = this[0]; i < this.length; i++){
if (max < this[i]) {
max = this[i];
}
return max;
};
Array.prototype.min = function(){
for (var i = 1, min = this[0]; i < this.length; i++){
if (min > this[i]) {
min = this[i];
}
return min;
};
Array.prototype.inArray = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
Array.prototype.max = function(){
for (var i = 1, max = this[0]; i < this.length; i++){
if (max < this[i]) {
max = this[i];
}
return max;
};
Array.prototype.min = function(){
for (var i = 1, min = this[0]; i < this.length; i++){
if (min > this[i]) {
min = this[i];
}
return min;
};
#3
mark
#4
Date.prototype.format = function(format) //author: meizz
{
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 hh:mm:ss"));
{
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 hh:mm:ss"));
#5
String.prototype.endsWith = function(character){
return (character == this.charAt(this.length - 1));
};
String.prototype.startsWith = function(character){
return (character == this.charAt(0);
};
return (character == this.charAt(this.length - 1));
};
String.prototype.startsWith = function(character){
return (character == this.charAt(0);
};
#6
在这儿发现一个比较多的。
http://ttyp.cnblogs.com/archive/2004/10/26/56730.html
http://www.cnblogs.com/Files/ttyp/Js-Lib.rar
http://ttyp.cnblogs.com/archive/2004/10/26/56730.html
http://www.cnblogs.com/Files/ttyp/Js-Lib.rar
#7
Function.prototype.bind = function(o){
var self = this;
var arg = Array.prototype.slice.call(arguments,1);
return function(){
self.apply(self, arg );
}
}
var self = this;
var arg = Array.prototype.slice.call(arguments,1);
return function(){
self.apply(self, arg );
}
}
#8
关于日期的一些,原创
<script language="JavaScript">
<!--
/*用相对不规则的字符串来创建日期对象,不规则的含义为:顺序包含年月日三个数值串,有间隔*/
String.prototype.parseDate = function(){
var regThree = /^\D*(\d{2,4})\D+(\d{1,2})\D+(\d{1,2})\D*$/;
var regSix = /^\D*(\d{2,4})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D*$/;
//var str = "";
var date = null;
if(regThree.test(this))
date = new Date(this.replace(/\s/g,"").replace(regThree,"$1/$2/$3"));
else if(regSix.test(this)){
str = this.match(regSix);
date = new Date(str[1],str[2]-1,str[3],str[4],str[5],str[6]);
}else return new Date();
return date;
}
/*
* 功能:根据输入表达式返回日期字符串
* 参数:dateFmt:字符串,由以下结构组成
* yy:长写年,YY:短写年mm:数字月,MM:英文月,dd:日,hh:时,
* mi:分,ss秒,ms:毫秒,we:汉字星期,WE:英文星期.
* isFmtWithZero : 是否用0进行格式化,true or false
*/
Date.prototype.parseString = function(dateFmt,isFmtWithZero){
dateFmt = (dateFmt == null?"yy-mm-dd" : dateFmt);
isFmtWithZero = (isFmtWithZero == null?true : isFmtWithZero);
if(typeof(dateFmt) != "string" )
throw (new Error(-1, 'parseString()方法需要字符串类型参数!'));
var weekArr=[["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
["SUN","MON","TUR","WED","THU","FRI","SAT"]];
var monthArr=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var str=dateFmt;
var o = {
"yy" : this.getFullYear(),
"YY" : this.getYear(),
"mm" : this.getMonth()+1,
"MM" : monthArr[this.getMonth()],
"dd" : this.getDate(),
"hh" : this.getHours(),
"mi" : this.getMinutes(),
"ss" : this.getSeconds(),
"we" : weekArr[0][this.getDay()],
"WE" : weekArr[1][this.getDay()]
}
for(var i in o){
str = str.replace(new RegExp(i,"g"),o[i].toString().fmtWithZero(isFmtWithZero));
}
str = str.replace(/ms/g,this.getMilliseconds().toString().fmtWithZeroD(isFmtWithZero));
return str;
}
/*将一位数字格式化成两位,如: 9 to 09*/
String.prototype.fmtWithZero = function(isFmtWithZero){
return (isFmtWithZero && /^\d$/.test(this))?"0"+this:this;
}
String.prototype.fmtWithZeroD = function(isFmtWithZero){
return (isFmtWithZero && /^\d{2}$/.test(this))?"00"+this:((isFmtWithZero && /^\d$/.test(this))?"0"+this:this);
}
/* 功能 : 返回与某日期相距N天(N个24小时)的日期
* 参数 : num number类型 可以为正负整数或者浮点数,默认为1;
* type 0(秒) or 1(天),默认为天
* 返回 : 新的PowerDate类型
*/
Date.prototype.dateAfter=function(num,type){
num = (num == null?1:num);
if(typeof(num)!="number") throw new Error(-1,"dateAfterDays(num,type)的num参数为数值类型.");
type = (type==null?1:type);
var arr = [1000,86400000];
return new Date(this.valueOf() + num*arr[type]);
}
//判断是否是闰年,返回true 或者 false
Date.prototype.isLeapYear = function (){
var year = this.getFullYear();
return (0==year%4 && ((year % 100 != 0)||(year % 400 == 0)));
}
//返回该月天数
Date.prototype.getDaysOfMonth = function (){
return (new Date(this.getFullYear(),this.getMonth()+1,0)).getDate();
}
//日期比较函数,参数date:为Date类型,如this日期晚于参数:1,相等:0 早于: -1
Date.prototype.dateCompare = function(date){
if(typeof(date) != "object" || !(/Date/.test(date.constructor)))
throw new Error(-1,"dateCompare(date)的date参数为Date类型.");
var d = this.getTime() - date.getTime();
return d>0?1:(d==0?0:-1);
}
/*功能:返回两日期之差
*参数:pd PowerDate对象
* type: 返回类别标识.yy:年,mm:月,ww:周,dd:日,hh:小时,mi:分,ss:秒,ms:毫秒
* intOrFloat :返回整型还是浮点型值 0:整型,不等于0:浮点型
* output : 输出提示,如:时间差为#周!
*/
Date.prototype.calDateDistance = function (date,type,intOrFloat,output){
if(typeof(date) != "object" || !(/Date/.test(date.constructor)))
throw new Error(-1,"calDateDistance(date,type,intOrFloat)的date参数为Date类型.");
type = (type==null?'dd':type);
if(!((new RegExp(type+",","g")).test("yy,mm,ww,dd,hh,mi,ss,ms,")))
throw new Error(-1,"calDateDistance(pd,type,intOrFloat,output)的type参数为非法.");
var iof = (intOrFloat==null?0:intOrFloat);
var num=0;
var o = {
"ww" : 7*86400000,
"dd" : 86400000,
"hh" : 3600000,
"mi" : 60000,
"ss" : 1000,
"ms" : 1
}
switch(type){
case "yy": num = this.getFullYear() - date.getFullYear(); break;
case "mm": num = (this.getFullYear() - date.getFullYear())*12+this.getMonth()-date.getMonth(); break;
default:
var sub = this.valueOf() - date.valueOf();
if (o[type])
num = (sub/o[type]).fmtRtnVal(iof);
break;
}
return (output ? output.replace(/#/g," "+num+" ") : num);
}
//返回整数或者两位小数的浮点数
Number.prototype.fmtRtnVal = function (intOrFloat){
return (intOrFloat == 0 ? Math.floor(this) : parseInt(this*100)/100);
}
//根据当前日期所在年和周数返回周日的日期
Date.prototype.RtnByWeekNum = function (weekNum){
if(typeof(weekNum) != "number")
throw new Error(-1,"RtnByWeekNum(weekNum)的参数是数字类型.");
var date = new Date(this.getFullYear(),0,1);
var week = date.getDay();
week = (week==0?7:week);
return date.dateAfter(weekNum*7-week,1);
}
//根据日期返回该日期所在年的周数
Date.prototype.getWeekNum = function (){
var dat = new Date(this.getFullYear(),0,1);
var week = dat.getDay();
week = (week==0?7:week);
var days = this.calDateDistance(dat,"dd")+1;
return ((days + 6 - this.getDay() - 7 + week)/7);
}
//-->
</script>
<script language="JavaScript">
<!--
var date1 = "2005-11-1";
var date3 = "2006-1-10 11 11 11".parseDate();
var date2 = "2005-12-30".parseDate();
//alert(date3);
alert(date3.calDateDistance(date2,null,null,"时间差为#天!"));
//-->
</script>
<script language="JavaScript">
<!--
/*用相对不规则的字符串来创建日期对象,不规则的含义为:顺序包含年月日三个数值串,有间隔*/
String.prototype.parseDate = function(){
var regThree = /^\D*(\d{2,4})\D+(\d{1,2})\D+(\d{1,2})\D*$/;
var regSix = /^\D*(\d{2,4})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D+(\d{1,2})\D*$/;
//var str = "";
var date = null;
if(regThree.test(this))
date = new Date(this.replace(/\s/g,"").replace(regThree,"$1/$2/$3"));
else if(regSix.test(this)){
str = this.match(regSix);
date = new Date(str[1],str[2]-1,str[3],str[4],str[5],str[6]);
}else return new Date();
return date;
}
/*
* 功能:根据输入表达式返回日期字符串
* 参数:dateFmt:字符串,由以下结构组成
* yy:长写年,YY:短写年mm:数字月,MM:英文月,dd:日,hh:时,
* mi:分,ss秒,ms:毫秒,we:汉字星期,WE:英文星期.
* isFmtWithZero : 是否用0进行格式化,true or false
*/
Date.prototype.parseString = function(dateFmt,isFmtWithZero){
dateFmt = (dateFmt == null?"yy-mm-dd" : dateFmt);
isFmtWithZero = (isFmtWithZero == null?true : isFmtWithZero);
if(typeof(dateFmt) != "string" )
throw (new Error(-1, 'parseString()方法需要字符串类型参数!'));
var weekArr=[["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
["SUN","MON","TUR","WED","THU","FRI","SAT"]];
var monthArr=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var str=dateFmt;
var o = {
"yy" : this.getFullYear(),
"YY" : this.getYear(),
"mm" : this.getMonth()+1,
"MM" : monthArr[this.getMonth()],
"dd" : this.getDate(),
"hh" : this.getHours(),
"mi" : this.getMinutes(),
"ss" : this.getSeconds(),
"we" : weekArr[0][this.getDay()],
"WE" : weekArr[1][this.getDay()]
}
for(var i in o){
str = str.replace(new RegExp(i,"g"),o[i].toString().fmtWithZero(isFmtWithZero));
}
str = str.replace(/ms/g,this.getMilliseconds().toString().fmtWithZeroD(isFmtWithZero));
return str;
}
/*将一位数字格式化成两位,如: 9 to 09*/
String.prototype.fmtWithZero = function(isFmtWithZero){
return (isFmtWithZero && /^\d$/.test(this))?"0"+this:this;
}
String.prototype.fmtWithZeroD = function(isFmtWithZero){
return (isFmtWithZero && /^\d{2}$/.test(this))?"00"+this:((isFmtWithZero && /^\d$/.test(this))?"0"+this:this);
}
/* 功能 : 返回与某日期相距N天(N个24小时)的日期
* 参数 : num number类型 可以为正负整数或者浮点数,默认为1;
* type 0(秒) or 1(天),默认为天
* 返回 : 新的PowerDate类型
*/
Date.prototype.dateAfter=function(num,type){
num = (num == null?1:num);
if(typeof(num)!="number") throw new Error(-1,"dateAfterDays(num,type)的num参数为数值类型.");
type = (type==null?1:type);
var arr = [1000,86400000];
return new Date(this.valueOf() + num*arr[type]);
}
//判断是否是闰年,返回true 或者 false
Date.prototype.isLeapYear = function (){
var year = this.getFullYear();
return (0==year%4 && ((year % 100 != 0)||(year % 400 == 0)));
}
//返回该月天数
Date.prototype.getDaysOfMonth = function (){
return (new Date(this.getFullYear(),this.getMonth()+1,0)).getDate();
}
//日期比较函数,参数date:为Date类型,如this日期晚于参数:1,相等:0 早于: -1
Date.prototype.dateCompare = function(date){
if(typeof(date) != "object" || !(/Date/.test(date.constructor)))
throw new Error(-1,"dateCompare(date)的date参数为Date类型.");
var d = this.getTime() - date.getTime();
return d>0?1:(d==0?0:-1);
}
/*功能:返回两日期之差
*参数:pd PowerDate对象
* type: 返回类别标识.yy:年,mm:月,ww:周,dd:日,hh:小时,mi:分,ss:秒,ms:毫秒
* intOrFloat :返回整型还是浮点型值 0:整型,不等于0:浮点型
* output : 输出提示,如:时间差为#周!
*/
Date.prototype.calDateDistance = function (date,type,intOrFloat,output){
if(typeof(date) != "object" || !(/Date/.test(date.constructor)))
throw new Error(-1,"calDateDistance(date,type,intOrFloat)的date参数为Date类型.");
type = (type==null?'dd':type);
if(!((new RegExp(type+",","g")).test("yy,mm,ww,dd,hh,mi,ss,ms,")))
throw new Error(-1,"calDateDistance(pd,type,intOrFloat,output)的type参数为非法.");
var iof = (intOrFloat==null?0:intOrFloat);
var num=0;
var o = {
"ww" : 7*86400000,
"dd" : 86400000,
"hh" : 3600000,
"mi" : 60000,
"ss" : 1000,
"ms" : 1
}
switch(type){
case "yy": num = this.getFullYear() - date.getFullYear(); break;
case "mm": num = (this.getFullYear() - date.getFullYear())*12+this.getMonth()-date.getMonth(); break;
default:
var sub = this.valueOf() - date.valueOf();
if (o[type])
num = (sub/o[type]).fmtRtnVal(iof);
break;
}
return (output ? output.replace(/#/g," "+num+" ") : num);
}
//返回整数或者两位小数的浮点数
Number.prototype.fmtRtnVal = function (intOrFloat){
return (intOrFloat == 0 ? Math.floor(this) : parseInt(this*100)/100);
}
//根据当前日期所在年和周数返回周日的日期
Date.prototype.RtnByWeekNum = function (weekNum){
if(typeof(weekNum) != "number")
throw new Error(-1,"RtnByWeekNum(weekNum)的参数是数字类型.");
var date = new Date(this.getFullYear(),0,1);
var week = date.getDay();
week = (week==0?7:week);
return date.dateAfter(weekNum*7-week,1);
}
//根据日期返回该日期所在年的周数
Date.prototype.getWeekNum = function (){
var dat = new Date(this.getFullYear(),0,1);
var week = dat.getDay();
week = (week==0?7:week);
var days = this.calDateDistance(dat,"dd")+1;
return ((days + 6 - this.getDay() - 7 + week)/7);
}
//-->
</script>
<script language="JavaScript">
<!--
var date1 = "2005-11-1";
var date3 = "2006-1-10 11 11 11".parseDate();
var date2 = "2005-12-30".parseDate();
//alert(date3);
alert(date3.calDateDistance(date2,null,null,"时间差为#天!"));
//-->
</script>
#9
学习..
#10
期待...
#11
String.prototype.cut = function(n){
var strTmp = "";
for(var i=0,l=this.length,k=0;(i<n);k++){
var ch = this.charAt(k);
if(ch.match(/[\x00-\x80]/)){
i += 1;
}
else{
i += 2;
}
strTmp += ch;
}
return strTmp;
}
截取定长字符串,一个汉字算两个字母宽..嘎嘎..得到的结果符还算整齐...
var strTmp = "";
for(var i=0,l=this.length,k=0;(i<n);k++){
var ch = this.charAt(k);
if(ch.match(/[\x00-\x80]/)){
i += 1;
}
else{
i += 2;
}
strTmp += ch;
}
return strTmp;
}
截取定长字符串,一个汉字算两个字母宽..嘎嘎..得到的结果符还算整齐...
#12
UP
#13
兄弟,打算整理了放哪里啊,一定要给我提个醒啊,上面的我先收了。
//--------------------------------------string-----------------------------------------
String.prototype.lTrim = function () {return this.replace(/^\s*/, "");}
String.prototype.rTrim = function () {return this.replace(/\s*$/, "");}
String.prototype.trim = function () {return this.rTrim().lTrim();}
String.prototype.endsWith = function(sEnd) {return (this.substr(this.length-sEnd.length)==sEnd);}
String.prototype.startsWith = function(sStart) {return (this.substr(0,sStart.length)==sStart);}
String.prototype.format = function()
{ var s = this; for (var i=0; i < arguments.length; i++)
{ s = s.replace("{" + (i) + "}", arguments[i]);}
return(s);}
String.prototype.removeSpaces = function()
{ return this.replace(/ /gi,'');}
String.prototype.removeExtraSpaces = function()
{ return(this.replace(String.prototype.removeExtraSpaces.re, " "));}
String.prototype.removeExtraSpaces.re = new RegExp("\\s+", "g");
String.prototype.removeSpaceDelimitedString = function(r)
{ var s = " " + this.trim() + " "; return s.replace(" " + r,"").rTrim();}
String.prototype.isEmpty = function() {return this.length==0;};
String.prototype.validateURL = function()
{ var urlRegX = /[^a-zA-Z0-9-]/g; return sURL.match(urlRegX, "");}
String.prototype.isEmail = function()
{ var emailReg = /^\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; return emailReg.test(this);}
String.prototype.isAlphaNumeric = function()
{ var alphaReg = /[^a-zA-Z0-9]/g; return !alphaReg.test(this);}
String.prototype.encodeURI = function()
{ var returnString; returnString = escape( this )
returnString = returnString.replace(/\+/g,"%2B"); return returnString
}
String.prototype.decodeURI = function() {return unescape(this)}
//--------------------------------------Array-----------------------------------------
Array.prototype.indexOf = function(p_var)
{
for (var i=0; i<this.length; i++)
{
if (this[i] == p_var)
{
return(i);
}
}
return(-1);
}
Array.prototype.exists = function(p_var) {return(this.indexOf(p_var) != -1);}
Array.prototype.queue = function(p_var) {this.push(p_var)}
Array.prototype.dequeue = function() {return(this.shift());}
Array.prototype.removeAt = function(p_iIndex) {return this.splice(p_iIndex, 1);}
Array.prototype.remove = function(o)
{
var i = this.indexOf(o); if (i>-1) this.splice(i,1); return (i>-1)
}
Array.prototype.clear = function()
{
var iLength = this.length;
for (var i=0; i < iLength; i++)
{
this.shift();
}
}
Array.prototype.addArray = function(p_a)
{
if (p_a)
{
for (var i=0; i < p_a.length; i++)
{
this.push(p_a[i]);
}
}
}
//--------------------------------------string-----------------------------------------
String.prototype.lTrim = function () {return this.replace(/^\s*/, "");}
String.prototype.rTrim = function () {return this.replace(/\s*$/, "");}
String.prototype.trim = function () {return this.rTrim().lTrim();}
String.prototype.endsWith = function(sEnd) {return (this.substr(this.length-sEnd.length)==sEnd);}
String.prototype.startsWith = function(sStart) {return (this.substr(0,sStart.length)==sStart);}
String.prototype.format = function()
{ var s = this; for (var i=0; i < arguments.length; i++)
{ s = s.replace("{" + (i) + "}", arguments[i]);}
return(s);}
String.prototype.removeSpaces = function()
{ return this.replace(/ /gi,'');}
String.prototype.removeExtraSpaces = function()
{ return(this.replace(String.prototype.removeExtraSpaces.re, " "));}
String.prototype.removeExtraSpaces.re = new RegExp("\\s+", "g");
String.prototype.removeSpaceDelimitedString = function(r)
{ var s = " " + this.trim() + " "; return s.replace(" " + r,"").rTrim();}
String.prototype.isEmpty = function() {return this.length==0;};
String.prototype.validateURL = function()
{ var urlRegX = /[^a-zA-Z0-9-]/g; return sURL.match(urlRegX, "");}
String.prototype.isEmail = function()
{ var emailReg = /^\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; return emailReg.test(this);}
String.prototype.isAlphaNumeric = function()
{ var alphaReg = /[^a-zA-Z0-9]/g; return !alphaReg.test(this);}
String.prototype.encodeURI = function()
{ var returnString; returnString = escape( this )
returnString = returnString.replace(/\+/g,"%2B"); return returnString
}
String.prototype.decodeURI = function() {return unescape(this)}
//--------------------------------------Array-----------------------------------------
Array.prototype.indexOf = function(p_var)
{
for (var i=0; i<this.length; i++)
{
if (this[i] == p_var)
{
return(i);
}
}
return(-1);
}
Array.prototype.exists = function(p_var) {return(this.indexOf(p_var) != -1);}
Array.prototype.queue = function(p_var) {this.push(p_var)}
Array.prototype.dequeue = function() {return(this.shift());}
Array.prototype.removeAt = function(p_iIndex) {return this.splice(p_iIndex, 1);}
Array.prototype.remove = function(o)
{
var i = this.indexOf(o); if (i>-1) this.splice(i,1); return (i>-1)
}
Array.prototype.clear = function()
{
var iLength = this.length;
for (var i=0; i < iLength; i++)
{
this.shift();
}
}
Array.prototype.addArray = function(p_a)
{
if (p_a)
{
for (var i=0; i < p_a.length; i++)
{
this.push(p_a[i]);
}
}
}
#14
楼上,一定通知你。
建议几点:
一、方法名最好模拟Java、.NET或VBScript的
如:
String.prototype.endsWith = function(){}; //Java和.NET中的String对象的endsWith方法。我建议不用endWith。
Object.prototype.isNumeric = function(){}; //VBScript中的IsNumeric方法
二、方法命名,因为是方法,所以遵守第一个单词字母小写,第二个大写。
这个String.prototype.trim = function(){};而不是Trim
Object.prototype.isNumeric = function() {};而不是IsNumeric
三、对已经有的方法,不封装,如
String对象已经有indexOf方法,就不必封装出一个inStr了。indexOf也很好用啊。
建议几点:
一、方法名最好模拟Java、.NET或VBScript的
如:
String.prototype.endsWith = function(){}; //Java和.NET中的String对象的endsWith方法。我建议不用endWith。
Object.prototype.isNumeric = function(){}; //VBScript中的IsNumeric方法
二、方法命名,因为是方法,所以遵守第一个单词字母小写,第二个大写。
这个String.prototype.trim = function(){};而不是Trim
Object.prototype.isNumeric = function() {};而不是IsNumeric
三、对已经有的方法,不封装,如
String对象已经有indexOf方法,就不必封装出一个inStr了。indexOf也很好用啊。
#15
也凑个热闹吧:
//排除数组重复项
Array.prototype.Unique = function()
{
var a = {}; for(var i=0; i<this.length; i++)
{
if(typeof a[this[i]] == "undefined")
a[this[i]] = 1;
}
this.length = 0;
for(var i in a)
this[this.length] = i;
return this;
};
//apply call
if(typeof(Function.prototype.apply)!="function")
{
Function.prototype.apply = function(obj, argu)
{
var s;
if(obj)
{
obj.constructor.prototype._caller=this;
s = "obj._caller";
}
else s = "this";
var a=[];
for(var i=0; i<argu.length; i++)
a[i] = "argu["+ i +"]";
return eval(s +"("+ a.join(",") +");");
};
Function.prototype.call = function(obj)
{
var a=[];
for(var i=1; i<arguments.length; i++)
a[i-1]=arguments[i];
return this.apply(obj, a);
};
}
if(typeof(Number.prototype.toFixed)!="function")
{
Number.prototype.toFixed = function(d)
{
var s=this+"";if(s.indexOf(".")==-1)s+=".";s+=new Array(d+1).join("0");
if (new RegExp("^((-|\\+)?\\d+(\\.\\d{0,"+ (d+1) +"})?)\\d*$").test(s))
{
s="0"+ RegExp.$1, pm=RegExp.$2, a=RegExp.$3.length, b=true;
if (a==d+2){a=s.match(/\d/g); if (parseInt(a[a.length-1])>4)
{
for(var i=a.length-2; i>=0; i--) {a[i] = parseInt(a[i])+1;
if(a[i]==10){a[i]=0; b=i!=1;} else break;}
}
s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");
}if(b)s=s.substr(1); return (pm+s).replace(/\.$/, "");} return this+"";
};
}
String.prototype.sub = function(n)
{
var r = /[^\x00-\xff]/g;
if(this.replace(r, "mm").length <= n) return this;
n = n - 3;
var m = Math.floor(n/2);
for(var i=m; i<this.length; i++)
{
if(this.substr(0, i).replace(r, "mm").length>=n)
{
return this.substr(0, i) +"...";
}
}
return this;
};
//排除数组重复项
Array.prototype.Unique = function()
{
var a = {}; for(var i=0; i<this.length; i++)
{
if(typeof a[this[i]] == "undefined")
a[this[i]] = 1;
}
this.length = 0;
for(var i in a)
this[this.length] = i;
return this;
};
//apply call
if(typeof(Function.prototype.apply)!="function")
{
Function.prototype.apply = function(obj, argu)
{
var s;
if(obj)
{
obj.constructor.prototype._caller=this;
s = "obj._caller";
}
else s = "this";
var a=[];
for(var i=0; i<argu.length; i++)
a[i] = "argu["+ i +"]";
return eval(s +"("+ a.join(",") +");");
};
Function.prototype.call = function(obj)
{
var a=[];
for(var i=1; i<arguments.length; i++)
a[i-1]=arguments[i];
return this.apply(obj, a);
};
}
if(typeof(Number.prototype.toFixed)!="function")
{
Number.prototype.toFixed = function(d)
{
var s=this+"";if(s.indexOf(".")==-1)s+=".";s+=new Array(d+1).join("0");
if (new RegExp("^((-|\\+)?\\d+(\\.\\d{0,"+ (d+1) +"})?)\\d*$").test(s))
{
s="0"+ RegExp.$1, pm=RegExp.$2, a=RegExp.$3.length, b=true;
if (a==d+2){a=s.match(/\d/g); if (parseInt(a[a.length-1])>4)
{
for(var i=a.length-2; i>=0; i--) {a[i] = parseInt(a[i])+1;
if(a[i]==10){a[i]=0; b=i!=1;} else break;}
}
s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");
}if(b)s=s.substr(1); return (pm+s).replace(/\.$/, "");} return this+"";
};
}
String.prototype.sub = function(n)
{
var r = /[^\x00-\xff]/g;
if(this.replace(r, "mm").length <= n) return this;
n = n - 3;
var m = Math.floor(n/2);
for(var i=m; i<this.length; i++)
{
if(this.substr(0, i).replace(r, "mm").length>=n)
{
return this.substr(0, i) +"...";
}
}
return this;
};
#16
meizz(梅花雪)来了,蓬筚生辉
#17
来玩
String.prototype.realLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
}
判断整型
String.prototype.isInteger = function()
{
//如果为空,则通过校验
if(this == "")
return true;
if(/^(\-?)(\d+)$/.test(this))
return true;
else
return false;
}
是否为空
String.prototype.isEmpty = function()
{
if(this.trim() == "")
return true;
else
return false;
}
String.prototype.realLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
}
判断整型
String.prototype.isInteger = function()
{
//如果为空,则通过校验
if(this == "")
return true;
if(/^(\-?)(\d+)$/.test(this))
return true;
else
return false;
}
是否为空
String.prototype.isEmpty = function()
{
if(this.trim() == "")
return true;
else
return false;
}
#18
hbhbhbhbhb1021(天外水火(我要多努力)) 版主多帖些,太少了,呵呵。
#19
学习
#20
工作日
Date.prototype.isWorkDay=function()
{
var year=this.getYear();
var month=this.getMonth();
var date=this.getDate();
var hour=this.getHours();
if(this.getDay()==6)
{
return false
}
if(this.getDay()==7)
{
return false
}
if((hour>7)&&(hour<17))
{
return true;
}
else
{
return false
}
}
var a=new Date();
alert(a.isWorkDay());
是否全为汉字
String.prototype.isAllChinese = function()
{
var pattern = /^([\u4E00-\u9FA5])*$/g;
if (pattern.test(this))
return true;
else
return false;
}
包含汉字
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}
全角转半角
<script language=javascript>
String.prototype.DBC2SBC=function()
{
var result = '';
for(var i=0;i<str.length;i++){
code = str.charCodeAt(i);//获取当前字符的unicode编码
if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
{
result += String.fromCharCode(str.charCodeAt(i) - 65248);//把全角字符的unicode编码转换为对应半角字符的unicode码
}else if (code == 12288)//空格
{
result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
}else
{
result += str.charAt(i);
}
}
return result;
}
var str="FSDFSDG广泛豆腐干"
alert(str)
alert(str.DBC2SBC())
</script>
Date.prototype.isWorkDay=function()
{
var year=this.getYear();
var month=this.getMonth();
var date=this.getDate();
var hour=this.getHours();
if(this.getDay()==6)
{
return false
}
if(this.getDay()==7)
{
return false
}
if((hour>7)&&(hour<17))
{
return true;
}
else
{
return false
}
}
var a=new Date();
alert(a.isWorkDay());
是否全为汉字
String.prototype.isAllChinese = function()
{
var pattern = /^([\u4E00-\u9FA5])*$/g;
if (pattern.test(this))
return true;
else
return false;
}
包含汉字
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}
全角转半角
<script language=javascript>
String.prototype.DBC2SBC=function()
{
var result = '';
for(var i=0;i<str.length;i++){
code = str.charCodeAt(i);//获取当前字符的unicode编码
if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
{
result += String.fromCharCode(str.charCodeAt(i) - 65248);//把全角字符的unicode编码转换为对应半角字符的unicode码
}else if (code == 12288)//空格
{
result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
}else
{
result += str.charAt(i);
}
}
return result;
}
var str="FSDFSDG广泛豆腐干"
alert(str)
alert(str.DBC2SBC())
</script>
#21
嘿嘿,大家都来给KimSoft(革命的小酒天天醉) 捧场啊
#22
强啊,学习!
#23
优化一下代码:
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}
==>
String.prototype.isContainChinese = function()
{
return /[\u4e00-\u9fa5\uf900-\ufa2d]/.test(this);
}
其它的类推优化
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}
==>
String.prototype.isContainChinese = function()
{
return /[\u4e00-\u9fa5\uf900-\ufa2d]/.test(this);
}
其它的类推优化
#24
支持,学习 ^_^
#25
的确,我的代码多用到变量
就拿这里来讲,这里有两句return true; return false;
我想这里就需要有两个对象来存储,浪费了资源。
而meizz的不管返回true或者false都应该存储在一个对象里。
TO meizz
除了这点之外,写成那种还有其他原因吗?
就拿这里来讲,这里有两句return true; return false;
我想这里就需要有两个对象来存储,浪费了资源。
而meizz的不管返回true或者false都应该存储在一个对象里。
TO meizz
除了这点之外,写成那种还有其他原因吗?
#26
减少消耗(少用了变量)
提高效率(少了if判断)
代码精简
提高效率(少了if判断)
代码精简
#27
楼上两位再帮我看看这个帖子。。。
http://community.csdn.net/Expert/topic/4609/4609496.xml?temp=.1486322
http://community.csdn.net/Expert/topic/4609/4609496.xml?temp=.1486322
#28
还有就是不要在正则里动不动就添加 g 模式:
/^([\u4E00-\u9FA5])*$/g //String.prototype.isAllChinese
这句正则里的 g 模式若是配合以 m 模式那还说得过去,你即然没有 m 那何必要添个 g ?
还有你用的是 * 若这一个空字符串你也认为是 isAllChinese ?所以应该用+
/^[\u4e00-\u9fa5\uf900-\ufa2d]+$/
var pattern = /[\u4E00-\u9FA5]/g; //String.prototype.isContainChinese
这句正则里加了一个无用的 g ,对系统消耗则相差甚大呀
/^([\u4E00-\u9FA5])*$/g //String.prototype.isAllChinese
这句正则里的 g 模式若是配合以 m 模式那还说得过去,你即然没有 m 那何必要添个 g ?
还有你用的是 * 若这一个空字符串你也认为是 isAllChinese ?所以应该用+
/^[\u4e00-\u9fa5\uf900-\ufa2d]+$/
var pattern = /[\u4E00-\u9FA5]/g; //String.prototype.isContainChinese
这句正则里加了一个无用的 g ,对系统消耗则相差甚大呀
#29
TO meizz(梅花雪)
灯泡(这个是帖图),以后我写代码要多注意了。
灯泡(这个是帖图),以后我写代码要多注意了。
#30
一看正则式就头大。一直将这个章节跳过去的,不知有没好的学习方法。
#31
呵呵,被挖走了
正则用处可大了,有时候能起到事半功倍的效果,.net里的正则比JS的还复杂
正则用处可大了,有时候能起到事半功倍的效果,.net里的正则比JS的还复杂
#32
先收藏下
#33
佩服各位高手的JS功力,象你们学习
#34
顶
#35
http://bbs.51js.com/viewthread.php?tid=1666
里面有一些可以整理下
里面有一些可以整理下
#36
公司光纤断了...偶正好出来办个事,偷空上个网.
#37
这个应该置顶
#38
up ^_^
#39
/******************************************************************************
* Array
******************************************************************************/
/* 返回数组中最大值 */
Array.prototype.max = function()
{
var i, max = this[0];
for (i = 1; i < this.length; i++)
{
if (max < this[i])
{
max = this[i];
}
}
return max;
};
/* 兼容ie5.0 */
if (!Array.prototype.push)
{
Array.prototype.push = function()
{
var startLength = this.length;
for (var i = 0; i < arguments.length; i++)
{
this[startLength + i] = arguments;
}
return this.length;
};
}
/* 返回 Array 对象内第一次出现 给定值 的索引值 */
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = 0;
}
else if (fromIndex < 0)
{
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex; i < this.length; i++)
{
if (this[i] === obj)
{
return i;
}
}
return-1;
};
}
/* 返回 Array 对象内最后一次出现 给定值 的索引值 */
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = this.length - 1;
}
else if (fromIndex < 0)
{
fromIndex=Math.max(0, this.length+fromIndex);
}
for (var i = fromIndex; i >= 0; i--)
{
if (this[i] === obj)
{
return i;
}
}
return -1;
};
}
/* Array.insert(值, 索引) */
Array.prototype.insertAt = function(o, i)
{
this.splice(i, 0, o);
};
/* Array.insertBefore(插入值, 值) */
Array.prototype.insertBefore = function(o, o2)
{
var i = this.indexOf(o2);
if (i == -1)
{
this.push(o);
}
else
{
this.splice(i, 0, o);
}
};
/* 删除给定元素 */
Array.prototype.remove = function(o)
{
var i = this.indexOf(o);
if (i != -1)
{
this.splice(i, 1);
}
};
/* 删除给定索引值位置的元素 */
Array.prototype.removeAt = function(i)
{
this.splice(i, 1);
};
/* 判断是否存在给定值 */
Array.prototype.contains = function(o)
{
return this.indexOf(o) != -1
};
/* 随机排序 */
Array.prototype.random = function ()
{
return this.sort(function(){return Math.random()*new Date%3-1})
};
/* 是否包含给定数组 */
Array.prototype.compare = function (a)
{
return this.toString().match(new RegExp("("+a.join("|")+")", "g"))
};
/* 复制数组 */
Array.prototype.copy = function(o)
{
return this.concat();
};
/* */
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
f.call(obj, this[i], i, this);
}
};
}
/* */
if (!Array.prototype.filter)
{
Array.prototype.filter = function(f, obj)
{
var l = this.length;
var res = [];
for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
res.push(this[i]);
}
}
return res;
};
}
/* */
if (!Array.prototype.map)
{
Array.prototype.map = function(f, obj)
{
var l = this.length;
var res = [];
for (var i = 0; i < l; i++)
{
res.push(f.call(obj, this[i], i, this));
}
return res;
};
}
/* */
if (!Array.prototype.some)
{
Array.prototype.some = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
return true;
}
}
return false;
};
}
/* */
if (!Array.prototype.every)
{
Array.prototype.every = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
if (!f.call(obj, this[i], i, this))
{
return false;
}
}
return true;
};
}
/******************************************************************************
* Date
******************************************************************************/
/* 格式化日期yyyy-MM-dd-mm-ss-q-S */
Date.prototype.Format = function(format)
{
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(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;
};
/* 是否周末 */
Date.prototype.isWeekend = function()
{
return (this.getDay() % 6) ? false : true;
};
/* 该月总共天数 */
Date.prototype.getMDate = function()
{
return (new Date(this.getFullYear(), this.getMonth()+1, 0).getDate())
};
/******************************************************************************
* Math
******************************************************************************/
/* Math.random()的重载函数 ; Math.random(n),返回小于n的整数 ; */
var _rnd = Math.random;
Math.random = function(n)
{
if (n == undefined)
{
return _rnd();
}
else if (n.toString().match(/^\-?\d*$/g))
{
return Math.round(_rnd()*n);
}
else
{
return null;
}
};
/******************************************************************************
* Number
******************************************************************************/
/* 返回数值的长度 */
Number.prototype.length = function()
{
return this.toString().length;
};
/* 将整数形式RGB颜色值转换为HEX形式 */
Number.prototype.toColorPart = function()
{
var digits = this.toString(16);
if (this < 16)
{
return '0' + digits;
}
return digits;
};
/* 返回000888形式 */
Number.prototype.format = function(n)
{
if (this.length() >= n)
{
return this;
}
return ((new Array(n).join("0")+(this|0)).slice(-n));
};
/******************************************************************************
* String
******************************************************************************/
/* 去掉字符串左端空格 */
String.prototype.lTrim = function()
{
return this.replace(/^\s*/, "");
};
/* 去掉字符串右端空格 */
String.prototype.rTrim = function()
{
return this.replace(/\s*$/, "");
};
/* 去掉字符串两端空格 */
String.prototype.Trim = function()
{
return this.replace(/^\s*|\s*$/g, "");
};
/* 返回字符串字节数 */
String.prototype.getBytesLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
};
/* 字符串首字母大写 */
String.prototype.capitalize = function()
{
return this.charAt(0).toUpperCase()+this.substr(1);
};
* Array
******************************************************************************/
/* 返回数组中最大值 */
Array.prototype.max = function()
{
var i, max = this[0];
for (i = 1; i < this.length; i++)
{
if (max < this[i])
{
max = this[i];
}
}
return max;
};
/* 兼容ie5.0 */
if (!Array.prototype.push)
{
Array.prototype.push = function()
{
var startLength = this.length;
for (var i = 0; i < arguments.length; i++)
{
this[startLength + i] = arguments;
}
return this.length;
};
}
/* 返回 Array 对象内第一次出现 给定值 的索引值 */
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = 0;
}
else if (fromIndex < 0)
{
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex; i < this.length; i++)
{
if (this[i] === obj)
{
return i;
}
}
return-1;
};
}
/* 返回 Array 对象内最后一次出现 给定值 的索引值 */
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = this.length - 1;
}
else if (fromIndex < 0)
{
fromIndex=Math.max(0, this.length+fromIndex);
}
for (var i = fromIndex; i >= 0; i--)
{
if (this[i] === obj)
{
return i;
}
}
return -1;
};
}
/* Array.insert(值, 索引) */
Array.prototype.insertAt = function(o, i)
{
this.splice(i, 0, o);
};
/* Array.insertBefore(插入值, 值) */
Array.prototype.insertBefore = function(o, o2)
{
var i = this.indexOf(o2);
if (i == -1)
{
this.push(o);
}
else
{
this.splice(i, 0, o);
}
};
/* 删除给定元素 */
Array.prototype.remove = function(o)
{
var i = this.indexOf(o);
if (i != -1)
{
this.splice(i, 1);
}
};
/* 删除给定索引值位置的元素 */
Array.prototype.removeAt = function(i)
{
this.splice(i, 1);
};
/* 判断是否存在给定值 */
Array.prototype.contains = function(o)
{
return this.indexOf(o) != -1
};
/* 随机排序 */
Array.prototype.random = function ()
{
return this.sort(function(){return Math.random()*new Date%3-1})
};
/* 是否包含给定数组 */
Array.prototype.compare = function (a)
{
return this.toString().match(new RegExp("("+a.join("|")+")", "g"))
};
/* 复制数组 */
Array.prototype.copy = function(o)
{
return this.concat();
};
/* */
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
f.call(obj, this[i], i, this);
}
};
}
/* */
if (!Array.prototype.filter)
{
Array.prototype.filter = function(f, obj)
{
var l = this.length;
var res = [];
for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
res.push(this[i]);
}
}
return res;
};
}
/* */
if (!Array.prototype.map)
{
Array.prototype.map = function(f, obj)
{
var l = this.length;
var res = [];
for (var i = 0; i < l; i++)
{
res.push(f.call(obj, this[i], i, this));
}
return res;
};
}
/* */
if (!Array.prototype.some)
{
Array.prototype.some = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
return true;
}
}
return false;
};
}
/* */
if (!Array.prototype.every)
{
Array.prototype.every = function(f, obj)
{
var l = this.length;
for (var i = 0; i < l; i++)
{
if (!f.call(obj, this[i], i, this))
{
return false;
}
}
return true;
};
}
/******************************************************************************
* Date
******************************************************************************/
/* 格式化日期yyyy-MM-dd-mm-ss-q-S */
Date.prototype.Format = function(format)
{
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(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;
};
/* 是否周末 */
Date.prototype.isWeekend = function()
{
return (this.getDay() % 6) ? false : true;
};
/* 该月总共天数 */
Date.prototype.getMDate = function()
{
return (new Date(this.getFullYear(), this.getMonth()+1, 0).getDate())
};
/******************************************************************************
* Math
******************************************************************************/
/* Math.random()的重载函数 ; Math.random(n),返回小于n的整数 ; */
var _rnd = Math.random;
Math.random = function(n)
{
if (n == undefined)
{
return _rnd();
}
else if (n.toString().match(/^\-?\d*$/g))
{
return Math.round(_rnd()*n);
}
else
{
return null;
}
};
/******************************************************************************
* Number
******************************************************************************/
/* 返回数值的长度 */
Number.prototype.length = function()
{
return this.toString().length;
};
/* 将整数形式RGB颜色值转换为HEX形式 */
Number.prototype.toColorPart = function()
{
var digits = this.toString(16);
if (this < 16)
{
return '0' + digits;
}
return digits;
};
/* 返回000888形式 */
Number.prototype.format = function(n)
{
if (this.length() >= n)
{
return this;
}
return ((new Array(n).join("0")+(this|0)).slice(-n));
};
/******************************************************************************
* String
******************************************************************************/
/* 去掉字符串左端空格 */
String.prototype.lTrim = function()
{
return this.replace(/^\s*/, "");
};
/* 去掉字符串右端空格 */
String.prototype.rTrim = function()
{
return this.replace(/\s*$/, "");
};
/* 去掉字符串两端空格 */
String.prototype.Trim = function()
{
return this.replace(/^\s*|\s*$/g, "");
};
/* 返回字符串字节数 */
String.prototype.getBytesLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
};
/* 字符串首字母大写 */
String.prototype.capitalize = function()
{
return this.charAt(0).toUpperCase()+this.substr(1);
};
#40
/* Function.call & applay 兼容ie5 参考prototype.js */
if (!Function.prototype.apply)
{
Function.prototype.apply = function(object, argu)
{
if (!object)
{
object = window;
}
if (!argu)
{
argu = new Array();
}
object.__apply__ = this;
var result = eval("object.__apply__(" + argu.join(", ") + ")");
object.__apply__ = null;
return result;
};
Function.prototype.call = function(object)
{
var argu = new Array();
for (var i = 1; i < arguments.length; i++)
{
argu[i-1] = arguments[i];
}
return this.apply(object, argu)
};
}
/* 为类蹭加set & get 方法, 参考bindows */
Function.READ = 1;
Function.WRITE = 2;
Function.READ_WRITE = 3;
Function.prototype.addProperty = function(sName, nReadWrite)
{
nReadWrite = nReadWrite || Function.READ_WRITE;
var capitalized = sName.charAt(0).toUpperCase() + sName.substr(1);
if (nReadWrite & Function.READ)
{
this.prototype["get"+capitalized] = new Function("","return this._" + sName + ";");
}
if (nReadWrite & Function.WRITE)
{
this.prototype["set"+capitalized] = new Function(sName,"this._" + sName + " = " + sName + ";");
}
};
/* 类继承, 参考bindows继承实现方式 */
Function.prototype.Extend = function(parentFunc, className)
{
var _parentFunc = parentFunc;
var p = this.prototype = new _parentFunc();
p.constructor = this;
if (className)
{
p._className = className;
}
else
{
p._className = "Object";
}
p.toString = function()
{
return "[object " + this._className + "]";
};
return p;
};
/* 实体化类 */
Function.prototype.Create = function()
{
return new this;
};
if (!Function.prototype.apply)
{
Function.prototype.apply = function(object, argu)
{
if (!object)
{
object = window;
}
if (!argu)
{
argu = new Array();
}
object.__apply__ = this;
var result = eval("object.__apply__(" + argu.join(", ") + ")");
object.__apply__ = null;
return result;
};
Function.prototype.call = function(object)
{
var argu = new Array();
for (var i = 1; i < arguments.length; i++)
{
argu[i-1] = arguments[i];
}
return this.apply(object, argu)
};
}
/* 为类蹭加set & get 方法, 参考bindows */
Function.READ = 1;
Function.WRITE = 2;
Function.READ_WRITE = 3;
Function.prototype.addProperty = function(sName, nReadWrite)
{
nReadWrite = nReadWrite || Function.READ_WRITE;
var capitalized = sName.charAt(0).toUpperCase() + sName.substr(1);
if (nReadWrite & Function.READ)
{
this.prototype["get"+capitalized] = new Function("","return this._" + sName + ";");
}
if (nReadWrite & Function.WRITE)
{
this.prototype["set"+capitalized] = new Function(sName,"this._" + sName + " = " + sName + ";");
}
};
/* 类继承, 参考bindows继承实现方式 */
Function.prototype.Extend = function(parentFunc, className)
{
var _parentFunc = parentFunc;
var p = this.prototype = new _parentFunc();
p.constructor = this;
if (className)
{
p._className = className;
}
else
{
p._className = "Object";
}
p.toString = function()
{
return "[object " + this._className + "]";
};
return p;
};
/* 实体化类 */
Function.prototype.Create = function()
{
return new this;
};
#41
mozilla 下没有的方法和属性~~
if (mozilla)
{
//////////////////////////////////////////////////////////////
/* HTMLObject.outerHTML || HTMLObject.innerText */
HTMLElement.prototype.__defineGetter__
(
"outerHTML",
function()
{
var str = "<" + this.tagName;
for (var i = 0; i < this.attributes.length; i++)
{
var attr = this.attributes[i];
str += " ";
str += attr.nodeName + "=" + '"' + attr.nodeValue + '"';
}
str += ">" + this.innerHTML + "</" + this.tagName + ">";
return str;
}
);
HTMLElement.prototype.__defineGetter__
(
"innerText",
function()
{
var rng = document.createRange();
rng.selectNode(this);
return rng.toString();
}
);
HTMLElement.prototype.__defineSetter__
(
"innerText",
function(txt)
{
var rng = document.createRange();
rng.selectNodeContents(this);
rng.deleteContents();
var newText = document.createTextNode(txt);
this.appendChild(newText);
}
);
/* event.srcElement || event.target */
Event.prototype.__defineGetter__
(
"srcElement",
function()
{
return this.target;
}
);
/* Object.attachEvent || Object.addEventListener
Object.detachEvent || Object.removeEventListener */
HTMLElement.prototype.attachEvent = Node.prototype.attachEvent = function(a, b)
{
return this.addEventListener(a.replace(/^on/i, ""), b,false);
};
HTMLElement.prototype.detachEvent = Node.prototype.detachEvent = function(a, b)
{
return this.removeEventListener(a.replace(/^on/i, ""), b, false);
};
/* XMLDocument.onreadystatechange, parseError
XMLDocument.createNode, load, loadXML,setProperty */
var _xmlDocPrototype = XMLDocument.prototype;
XMLDocument.prototype.__defineSetter__
(
"onreadystatechange",
function(f)
{
if (this._onreadystatechange)
{
this.removeEventListener("load", this._onreadystatechange, false);
}
this._onreadystatechange = f;
if (f)
{
this.addEventListener("load", f, false);
}
return f;
}
);
XMLDocument.prototype.createNode = function(aType, aName, aNamespace)
{
switch(aType)
{
case 1:
if (aNamespace && aNamespace != "")
{
return this.createElementNS(aNamespace, aName);
}
else
{
return this.createElement(aName);
}
case 2:
if (aNamespace && aNamespace != "")
{
return this.createAttributeNS(aNamespace,aName);
}
else
{
return this.createAttribute(aName);
}
case 3:
default:
return this.createTextNode("");
}
};
XMLDocument.prototype.__realLoad = _xmlDocPrototype.load;
XMLDocument.prototype.load = function(sUri)
{
this.readyState = 0;
this.__realLoad(sUri);
};
XMLDocument.prototype.loadXML = function(s)
{
var doc2 = (new DOMParser).parseFromString(s, "text/xml");
while (this.hasChildNodes())
{
this.removeChild(this.lastChild);
}
var cs=doc2.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++)
{
this.appendChild(this.importNode(cs[i], true));
}
};
XMLDocument.prototype.setProperty = function(sName, sValue)
{
if (sName == "SelectionNamespaces")
{
this._selectionNamespaces = {};
var parts = sValue.split(/\s+/);
var re= /^xmlns\:([^=]+)\=((\"([^\"]*)\")|(\'([^\']*)\'))$/;
for (var i = 0; i < parts.length; i++)
{
re.test(parts[i]);
this._selectionNamespaces[RegExp.$1] = RegExp.$4 || RegExp.$6;
}
}
};
var _mozHasParseError = function(oDoc)
{
return !oDoc.documentElement || oDoc.documentElement.localName=="parsererror"
&& oDoc.documentElement.getAttribute("xmlns")=="http://www.mozilla.org/newlayout/xml/parsererror.xml";
};
XMLDocument.prototype.__defineGetter__
(
"parseError",
function()
{
var hasError = _mozHasParseError(this);
var res = {
errorCode : 0,
filepos : 0,
line : 0,
linepos : 0,
reason : "",
srcText : "",
url : ""
};
if (hasError)
{
res.errorCode = -1;
try
{
res.srcText = this.getElementsByTagName("sourcetext")[0].firstChild.data;
res.srcText = res.srcText.replace(/\n\-\^$/, "");
}
catch(ex)
{
res.srcText = "";
}
try
{
var s = this.documentElement.firstChild.data;
var re = /XML Parsing Error\:(.+)\nLocation\:(.+)\nLine Number(\d+)\,Column(\d+)/;
var a = re.exec(s);
res.reason = a[1];
res.url = a[2];
res.line = a[3];
res.linepos = a[4];
}
catch(ex)
{
res.reason="Unknown";
}
}
return res;
}
);
/* Attr.xml */
Attr.prototype.__defineGetter__
(
"xml",
function()
{
var nv = (new XMLSerializer).serializeToString(this);
return this.nodeName + "=\""+nv.replace(/\"/g,""")+"\"";
}
);
/* Node.xml, text, baseName
Node.selectNodes, selectSingleNode, transformNode, transformNodeToObject */
Node.prototype.__defineGetter__
(
"xml",
function()
{
return (new XMLSerializer).serializeToString(this);
}
);
Node.prototype.__defineGetter__
(
"text",
function()
{
var cs = this.childNodes;
var l = cs.length;
var sb = new Array(l);
for (var i = 0; i < l; i++)
{
sb[i] = cs[i].text.replace(/^\n/, "");
}
return sb.join("");
}
);
Node.prototype.__defineGetter__
(
"baseName",
function()
{
var lParts = this.nodeName.split(":");
return lParts[lParts.length-1];
}
);
Node.prototype.selectNodes = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;
if (doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if (s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}
return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}
var xpRes = doc.evaluate(sExpr, this, nsRes2, 5, null);
var res=[];
var item;
while ((item = xpRes.iterateNext()))
res.push(item);
return res;
};
Node.prototype.selectSingleNode = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;
if(doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if(s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}
return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}
var xpRes = doc.evaluate(sExpr, this, nsRes2, 9, null);
return xpRes.singleNodeValue;
};
Node.prototype.transformNode = function(oXsltNode)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var processor = new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df = processor.transformToFragment(this, doc);
return df.xml;
};
Node.prototype.transformNodeToObject = function(oXsltNode, oOutputDocument)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var outDoc = oOutputDocument.nodeType==9 ? oOutputDocument : oOutputDocument.ownerDocument;
var processor=new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df=processor.transformToFragment(this,doc);
while (oOutputDocument.hasChildNodes())
{
oOutputDocument.removeChild(oOutputDocument.lastChild);
}
var cs=df.childNodes;
var l=cs.length;
for(var i=0; i<l; i++)
{
oOutputDocument.appendChild(outDoc.importNode(cs[i],true));
}
};
/* TextNode.text */
Text.prototype.__defineGetter__
(
"text",
function()
{
return this.nodeValue;
}
);
//////////////////////////////////////////////////////////////
}
if (mozilla)
{
//////////////////////////////////////////////////////////////
/* HTMLObject.outerHTML || HTMLObject.innerText */
HTMLElement.prototype.__defineGetter__
(
"outerHTML",
function()
{
var str = "<" + this.tagName;
for (var i = 0; i < this.attributes.length; i++)
{
var attr = this.attributes[i];
str += " ";
str += attr.nodeName + "=" + '"' + attr.nodeValue + '"';
}
str += ">" + this.innerHTML + "</" + this.tagName + ">";
return str;
}
);
HTMLElement.prototype.__defineGetter__
(
"innerText",
function()
{
var rng = document.createRange();
rng.selectNode(this);
return rng.toString();
}
);
HTMLElement.prototype.__defineSetter__
(
"innerText",
function(txt)
{
var rng = document.createRange();
rng.selectNodeContents(this);
rng.deleteContents();
var newText = document.createTextNode(txt);
this.appendChild(newText);
}
);
/* event.srcElement || event.target */
Event.prototype.__defineGetter__
(
"srcElement",
function()
{
return this.target;
}
);
/* Object.attachEvent || Object.addEventListener
Object.detachEvent || Object.removeEventListener */
HTMLElement.prototype.attachEvent = Node.prototype.attachEvent = function(a, b)
{
return this.addEventListener(a.replace(/^on/i, ""), b,false);
};
HTMLElement.prototype.detachEvent = Node.prototype.detachEvent = function(a, b)
{
return this.removeEventListener(a.replace(/^on/i, ""), b, false);
};
/* XMLDocument.onreadystatechange, parseError
XMLDocument.createNode, load, loadXML,setProperty */
var _xmlDocPrototype = XMLDocument.prototype;
XMLDocument.prototype.__defineSetter__
(
"onreadystatechange",
function(f)
{
if (this._onreadystatechange)
{
this.removeEventListener("load", this._onreadystatechange, false);
}
this._onreadystatechange = f;
if (f)
{
this.addEventListener("load", f, false);
}
return f;
}
);
XMLDocument.prototype.createNode = function(aType, aName, aNamespace)
{
switch(aType)
{
case 1:
if (aNamespace && aNamespace != "")
{
return this.createElementNS(aNamespace, aName);
}
else
{
return this.createElement(aName);
}
case 2:
if (aNamespace && aNamespace != "")
{
return this.createAttributeNS(aNamespace,aName);
}
else
{
return this.createAttribute(aName);
}
case 3:
default:
return this.createTextNode("");
}
};
XMLDocument.prototype.__realLoad = _xmlDocPrototype.load;
XMLDocument.prototype.load = function(sUri)
{
this.readyState = 0;
this.__realLoad(sUri);
};
XMLDocument.prototype.loadXML = function(s)
{
var doc2 = (new DOMParser).parseFromString(s, "text/xml");
while (this.hasChildNodes())
{
this.removeChild(this.lastChild);
}
var cs=doc2.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++)
{
this.appendChild(this.importNode(cs[i], true));
}
};
XMLDocument.prototype.setProperty = function(sName, sValue)
{
if (sName == "SelectionNamespaces")
{
this._selectionNamespaces = {};
var parts = sValue.split(/\s+/);
var re= /^xmlns\:([^=]+)\=((\"([^\"]*)\")|(\'([^\']*)\'))$/;
for (var i = 0; i < parts.length; i++)
{
re.test(parts[i]);
this._selectionNamespaces[RegExp.$1] = RegExp.$4 || RegExp.$6;
}
}
};
var _mozHasParseError = function(oDoc)
{
return !oDoc.documentElement || oDoc.documentElement.localName=="parsererror"
&& oDoc.documentElement.getAttribute("xmlns")=="http://www.mozilla.org/newlayout/xml/parsererror.xml";
};
XMLDocument.prototype.__defineGetter__
(
"parseError",
function()
{
var hasError = _mozHasParseError(this);
var res = {
errorCode : 0,
filepos : 0,
line : 0,
linepos : 0,
reason : "",
srcText : "",
url : ""
};
if (hasError)
{
res.errorCode = -1;
try
{
res.srcText = this.getElementsByTagName("sourcetext")[0].firstChild.data;
res.srcText = res.srcText.replace(/\n\-\^$/, "");
}
catch(ex)
{
res.srcText = "";
}
try
{
var s = this.documentElement.firstChild.data;
var re = /XML Parsing Error\:(.+)\nLocation\:(.+)\nLine Number(\d+)\,Column(\d+)/;
var a = re.exec(s);
res.reason = a[1];
res.url = a[2];
res.line = a[3];
res.linepos = a[4];
}
catch(ex)
{
res.reason="Unknown";
}
}
return res;
}
);
/* Attr.xml */
Attr.prototype.__defineGetter__
(
"xml",
function()
{
var nv = (new XMLSerializer).serializeToString(this);
return this.nodeName + "=\""+nv.replace(/\"/g,""")+"\"";
}
);
/* Node.xml, text, baseName
Node.selectNodes, selectSingleNode, transformNode, transformNodeToObject */
Node.prototype.__defineGetter__
(
"xml",
function()
{
return (new XMLSerializer).serializeToString(this);
}
);
Node.prototype.__defineGetter__
(
"text",
function()
{
var cs = this.childNodes;
var l = cs.length;
var sb = new Array(l);
for (var i = 0; i < l; i++)
{
sb[i] = cs[i].text.replace(/^\n/, "");
}
return sb.join("");
}
);
Node.prototype.__defineGetter__
(
"baseName",
function()
{
var lParts = this.nodeName.split(":");
return lParts[lParts.length-1];
}
);
Node.prototype.selectNodes = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;
if (doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if (s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}
return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}
var xpRes = doc.evaluate(sExpr, this, nsRes2, 5, null);
var res=[];
var item;
while ((item = xpRes.iterateNext()))
res.push(item);
return res;
};
Node.prototype.selectSingleNode = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;
if(doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if(s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}
return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}
var xpRes = doc.evaluate(sExpr, this, nsRes2, 9, null);
return xpRes.singleNodeValue;
};
Node.prototype.transformNode = function(oXsltNode)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var processor = new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df = processor.transformToFragment(this, doc);
return df.xml;
};
Node.prototype.transformNodeToObject = function(oXsltNode, oOutputDocument)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var outDoc = oOutputDocument.nodeType==9 ? oOutputDocument : oOutputDocument.ownerDocument;
var processor=new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df=processor.transformToFragment(this,doc);
while (oOutputDocument.hasChildNodes())
{
oOutputDocument.removeChild(oOutputDocument.lastChild);
}
var cs=df.childNodes;
var l=cs.length;
for(var i=0; i<l; i++)
{
oOutputDocument.appendChild(outDoc.importNode(cs[i],true));
}
};
/* TextNode.text */
Text.prototype.__defineGetter__
(
"text",
function()
{
return this.nodeValue;
}
);
//////////////////////////////////////////////////////////////
}
#42
好多啊,谢谢楼上支持。