如下內容來自,真心不錯的系列博文,但願原樓主繼續分享:javascript
http://7788a.iteye.com/blog/1610177 css
1、JavaScript跨平臺事件html
對於跨平臺事件咱們通常這麼寫(只例舉添加事件):java
function addEventHandler(oTarget, sEventType, fnHandler){ if(oTarget.addEventListener){ oTarget.addEventListener(sEventType,fnHandler,false); } else if(oTarget.attachEvent){ oTarget.attachEvent("on"+sEventType,fnHandler); } else{ oTarget["on"+sEventType]=fnHandler; } }
那麼下面這段代碼的效果是什麼樣的呢?數組
<div id="test">Test</div> ... var oDiv=document.getElementById("test"); addEventHandler(oDiv,"mouseover",function(){ alert("over "+this.id); });
因爲IE的this問題,在IE中果斷地彈出了 over undefined,因此跨平臺的事件更好的寫法是這樣的:瀏覽器
function addEventHandler(oTarget, sEventType, fnHandler){ if(oTarget.addEventListener){ oTarget.addEventListener(sEventType,fnHandler,false); } else if(oTarget.attachEvent){ oTarget.attachEvent("on"+sEventType,function(){ return fnHandler.call(oTarget,window.event); }); } else{ oTarget["on"+sEventType]=fnHandler; } }
2、合併兩個Array並去掉重複項app
Array.prototype.unique = function() { var a = this.concat(); for(var i=0; i<a.length; ++i) { for(var j=i+1; j<a.length; ++j) { if(a[i] === a[j]) a.splice(j, 1); } } return a; };//Demo var array1 = ["a","b"];var array2 = ["b", "c"];var array3 = array1.concat(array2).unique();// ["a","b","c"]
3、typeof === "undefined" vs. != null異步
if(typeof neverDeclared == "undefined") //no errors if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined
so,typeof === "undefined" is better!函數
4、setTimeout(fn, 0)的意義this
瀏覽器同時要作不少事,這些事情以隊列的方式存在,執行JavaScript只是其中之一,setTimeout(fn, 0)表面上看是當即執行的意思,但實際上只是在瀏覽器事件隊列中添加了一個新的事件,因爲隊列是先進先出,因此fn會等等到當前隊列中的事件執行完後再執行。因爲JavaScript的定時器回調函數是異步執行的,因此產生的效果就是等頁面上同步事件(包括頁面渲染與同步JS代碼)執行完以後再執行。
一個簡單的示例:
<script type="text/javascript"> //one document.getElementById("imgTest").style.borderBottom="5px solid #000"; //two setTimeout(function(){ document.getElementById("imgTest").style.borderBottom="5px solid #000"; }, 0);</script> <img src="http://jscode.chinacxy.com/img_lib/m_400_600_01.jpg" id="imgTest" alt=""/>
one會報錯,由於頁面執行到這裏時尚未img,但two卻能夠。
5、加強版取URL中的參數
function getQueryString() { var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m; while (m = re.exec(queryString)) { result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } return result; }// demo var myParam = getQueryString()["myParam"];
6、檢查一個object是不是jQuery object
if(obj instanceof jQuery)
7、檢查一個數是否爲整數或浮點數
function isInt(n) { return typeof n === 'number' && n % 1 == 0; }// or ,this support ie3 function isInt(n) { return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n); }function isFloat (n) { return n===+n && n!==(n|0); }
8、用JavaScript添加style節點
var css = 'h1 { background: red; }', head = document.getElementsByTagName('head')[0], style = document.createElement('style'); style.type = 'text/css';if(style.styleSheet){ style.styleSheet.cssText = css; }else{ style.appendChild(document.createTextNode(css)); } head.appendChild(style);
9、如何跳出雙重循環
function foo () { dance: for(var k = 0; k < 4; k++){ for(var m = 0; m < 4; m++){ if(m == 2){ break dance; } } } }
10、把一個Array追加到另外一個Array上
var a=[1,2],b=[3,4,5]; a.push.apply(a,b);/*a: [1, 2, 3, 4, 5]*/
11、用jQuery把頁面上的一個tag換成另外一個tag
如把頁面上全部的code換爲pre:
<code> A </code> <code> B </code> <code> C </code> //change to<pre> A </pre> <pre> A </pre> <pre> A </pre>
jQuery代碼:
$('code').contents().unwrap().wrap('<pre/>');//or $('code').replaceWith(function(){ return $("<pre />").append($(this).contents()); });
12、取數組中的最小值和最大值
var arr = new Array(); arr[0] = 100; arr[1] = 0; arr[2] = 50;var min = Math.min.apply(null, arr), max = Math.max.apply(null, arr);
十3、取兩個數組交集
/* finds the intersection of * two arrays in a simple fashion. * * PARAMS * a - first array, must already be sorted * b - second array, must already be sorted * * NOTES * * Should have O(n) operations, where n is * n = MIN(a.length(), b.length()) */ function arrayIntersection(a, b) { var ai=0, bi=0; var result = new Array(); while( ai < a.length && bi < b.length ) { if (a[ai] < b[bi] ){ ai++; } else if (a[ai] > b[bi] ){ bi++; } else /* they're equal */ { result.push(a[ai]); ai++; bi++; } } return result; } console.log(arrayIntersection([1,2,3],[2,3,4,5,6]));//[2,3]
註釋中已經說明了,傳入的數組要已經排過序的。
十4、統計一個字符串中某段子串出現的次數
var temp = "This is a string.";var count = temp.match(/is/g).length;
十5、方法返回多個值
//One var mValues= function(){ var a ="a"; var b = "b"; return [a, b]; };var values= mValues();var valOne= values[0];var valTwo = values[1];//Two var mValues= function(){ var a= "a"; var b = "b"; return { 'a': a, 'b': b }; };var values= mValues();var valOne= values.a;var valTwo = values.b;
十6、Array迭代器
function createIterator(x) { var i = 0; return function(){ return x[i++]; }; }var iterator=createIterator(['a','b','c','d','e','f','g']);var current;while(current=iterator()) { console.log(current); }
注意,若是數組中有0、false、""、null、NaN迭代器將會中止。
十7、根據日計算年齡
function getAge(dateString) { var today = new Date(); var birthDate = new Date(dateString); var age = today.getFullYear() - birthDate.getFullYear(); var m = today.getMonth() - birthDate.getMonth(); if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { age--; } return age; }
console.log(getAge("2005,8,1"));//6
十8、判斷當前頁面是否被放入了iframe中
if(self==top){ //not in iframe }else{ //in iframe }
這段代碼能夠用來防止網頁被放入iframe中,不過若是別人定義了self和top變量覆蓋了瀏覽器默認值可能會失效。
十9、把arguments轉換爲Array
var args = Array.prototype.slice.call(arguments, 0);
二10、日期格式化
來源:javascript日期格式化函數,跟C#中的使用方法相似
Date.prototype.toString=function(format,loc){ var time={}; time.Year=this.getFullYear(); time.TYear=(""+time.Year).substr(2); time.Month=this.getMonth()+1; time.TMonth=time.Month<10?"0"+time.Month:time.Month; time.Day=this.getDate(); time.TDay=time.Day<10?"0"+time.Day:time.Day; time.Hour=this.getHours(); time.THour=time.Hour<10?"0"+time.Hour:time.Hour; time.hour=time.Hour<13?time.Hour:time.Hour-12; time.Thour=time.hour<10?"0"+time.hour:time.hour; time.Minute=this.getMinutes(); time.TMinute=time.Minute<10?"0"+time.Minute:time.Minute; time.Second=this.getSeconds(); time.TSecond=time.Second<10?"0"+time.Second:time.Second; time.Millisecond=this.getMilliseconds(); time.Week=this.getDay(); var MMMArrEn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; var MMMArr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]; var WeekArrEn=["Sun","Mon","Tue","Web","Thu","Fri","Sat"]; var WeekArr=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]; var oNumber=time.Millisecond/1000; if(format!=undefined && format.replace(/\s/g,"").length>0){ if(loc!=undefined && loc =="en"){ MMMArr=MMMArrEn.slice(0); WeekArr=WeekArrEn.slice(0); } format=format .replace(/yyyy/ig,time.Year) .replace(/yyy/ig,time.Year) .replace(/yy/ig,time.TYear) .replace(/y/ig,time.TYear) .replace(/MMM/g,MMMArr[time.Month-1]) .replace(/MM/g,time.TMonth) .replace(/M/g,time.Month) .replace(/dd/ig,time.TDay) .replace(/d/ig,time.Day) .replace(/HH/g,time.THour) .replace(/H/g,time.Hour) .replace(/hh/g,time.Thour) .replace(/h/g,time.hour) .replace(/mm/g,time.TMinute) .replace(/m/g,time.Minute) .replace(/ss/ig,time.TSecond) .replace(/s/ig,time.Second) .replace(/fff/ig,time.Millisecond) .replace(/ff/ig,oNumber.toFixed(2)*100) .replace(/f/ig,oNumber.toFixed(1)*10) .replace(/EEE/g,WeekArr[time.Week]); } else{ format=time.Year+"-"+time.Month+"-"+time.Day+" "+time.Hour+":"+time.Minute+":"+time.Second; } return format; }var d=new Date(); console.log(d.toString()); //2012-7-27 9:26:52 console.log(d.toString("")); //2012-7-27 9:26:52 console.log(d.toString("yyyy-MM-dd HH:mm:ss")); //2012-07-27 09:26:52 console.log(d.toString("yyyy年MM月dd日 HH:mm:ss")); //2012年07月27日 09:26:52 console.log(d.toString("yyyy-MM-dd HH:mm:ss fff")); //2012-07-27 09:26:52 237 console.log(d.toString("yyyy年 MMM dd EEE")); //2012年 七月 27 星期五 console.log(d.toString("yyyy MMM dd EEE","en")); //2012 Jul 27 Fri