1.數組
1.1返回數組索引indeOf
if(!Array.prototype.indexOf) {//for IE<br />Array.prototype.indexOf=function(el,index) {<br />var length=this.length;<br />index=index >> 0;<br />if(index<0)index=length+index;<br />for(var i=index;i<length;i++) {<br />var current=this[i];<br />if(typeof(current)!=='undefined' ||i in this) {<br />if(current===el)<br />return i;<br />}<br />}<br />return -1;<br />}<br />}<br />var arr=[1,3,5,6,2,6];<br />alert(arr.indexOf(6));<br />alert(arr.indexOf(6,-2));<br />alert(arr.indexOf(5,3));<br />
1.2.map,
if(!Array.prototype.map) {<br />Array.prototype.map=function(callback,thisObj) {<br />if(typeof(callback)!=="function")<br />throw Error("argument [callback] is not a function");<br />var length=this.length;<br />var result=new Array(length);<br />for(var i=0;i<length;i++) {<br />result[i]=callback.call(thisObj,this[i],i,this);<br />}<br />return result;<br />}<br />}<br />var arr=[1,2,3];<br />var narr=arr.map(function(a) {<br />return a*a;<br />});<br />alert(narr);
1.3
if(!Array.prototype.forEach) {<br /> Array.prototype.forEach=function(callback,thisObj) {<br /> if(typeof(callback)!=="function")<br /> throw Error("argument [callback] is not a function");<br /> var len=this.length;<br /> for(var i=0;i<len;i++)<br /> callback.call(thisObj,this[i],i,this);<br /> }<br />}<br />var arr=[1,3,5];<br />arr.forEach(function(a,i) {<br /> alert(i+":"+a);<br />});<br />
2.日期格式化
if(!Date.format){//日期格式化<br /> Date.prototype.format = function(format)<br /> {<br /> var o =<br /> {<br /> "M+" : this.getMonth()+1, //month<br /> "d+" : this.getDate(), //day<br /> "h+" : this.getHours(), //hour<br /> "m+" : this.getMinutes(), //minute<br /> "s+" : this.getSeconds(), //second<br /> "q+" : Math.floor((this.getMonth()+3)/3), //quarter<br /> "S" : this.getMilliseconds() //millisecond<br /> }<br /> if(/(y+)/.test(format))<br /> format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));<br /> for(var k in o)<br /> if(new RegExp("("+ k +")").test(format))<br /> format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));<br /> return format;<br /> };<br />}<br />var d=new Date();<br />alert(d.format("yy-mm-dd"));
3.String.trim()
if(!String.prototype.trim) {//Firefox<br /> String.prototype.trim=function() {<br /> return this.replace(/^/s+|/s+$/g,"");<br /> };<br />}<br />var str=" /t aaaaa ";<br />alert(str.length);<br />alert(str.trim().length);<br />
4.相容IE的setTimeout多參數:
if(window.ActiveXObject) {<br /> (function(f){<br /> window.setTimeout =f(window.setTimeout);<br /> window.setInterval =f(window.setInterval);<br /> })(function(f){<br /> return function(c,t){<br /> var a=[].slice.call(arguments,2);<br /> return f(function(){<br /> c.apply(this,a)},t)<br /> }<br /> });<br />}
2009-10-30:1.將相容ie的setTimeout判斷從document.all改為window.ActiveXObject
2.將幾個數組方法的迴圈取length放到單獨的變數中
待續(LastModifid:2009-12-24)