收集JavaScript内置对象扩展原型函数2

来源:互联网 发布:共产主义是什么知乎 编辑:程序博客网 时间:2024/06/05 22:46

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;
};


Function.prototype.bind = function(o){
    var self = this;
    var arg = Array.prototype.slice.call(arguments,1);
    return function(){
        self.apply(self, arg );
   }
}

String.prototype.cut = function(n){
var strTmp = "";
for(var i=0,l=this.length,k=0;(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


建议几点:
一、方法名最好模拟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也很好用啊。


//排除数组重复项
Array.prototype.Unique = function()
{
var a = {}; for(var i=0; i

//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

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


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;
}


工作日
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;
}

全角转半角

 

 

/******************************************************************************
*   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);
};

 

/* 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;
};

 

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,"&quot;")+"/"";
}
);


/* 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;
}
);

//////////////////////////////////////////////////////////////
}

原创粉丝点击