Javascript學習總結-技巧、實用函數、簡介方法、編程細

整理JavaScript方面的一些技巧,比較實用的函數,常見功能實現方法,僅作參考


變量轉換
  1. //edit http://www.lai18.com   
  2. var myVar  = "3.14159",  
  3. str   = ""+ myVar,// to string  
  4. int   = ~~myVar, // to integer  
  5. float  = 1*myVar, // to float  
  6. bool  = !!myVar, /* to boolean - any string with length 
  7. and any number except 0 are true */  
  8. array  = [myVar]; // to array  
但是轉換日期(new Date(myVar))和正則表達式(new RegExp(myVar))必須使用構造函數,創建正則表達式的時候要使用/pattern/flags這樣的簡化形式。 

取整同時轉換成數值型 
  1. //edit http://www.lai18.com   
  2. //字符型變量參與運算時,JS會自動將其轉換爲數值型(如果無法轉化,變爲NaN)  
  3.     '10.567890' | 0  
  4.     //結果: 10  
  5.     //JS裏面的所有數值型都是雙精度浮點數,因此,JS在進行位運算時,會首先將這些數字運算數轉換爲整數,然後再執行運算  
  6.     //| 是二進制或, x|0 永遠等於x;^爲異或,同0異1,所以 x^0 還是永遠等於x;至於~是按位取反,搞了兩次以後值當然是一樣的  
  7.     '10.567890' ^ 0      
  8.     //結果: 10  
  9.     - 2.23456789 | 0  
  10.     //結果: -2  
  11.     ~~-2.23456789  
  12.     //結果: -2  

日期轉數值
  1. //JS本身時間的內部表示形式就是Unix時間戳,以毫秒爲單位記錄着當前距離1970年1月1日0點的時間單位  
  2.     var d = +new Date(); //1295698416792  

類數組對象轉數組
  1. var arr =[].slice.call(arguments)  

下面的實例用的更絕
  1. function test() {  
  2.   var res = ['item1''item2']  
  3.   res = res.concat(Array.prototype.slice.call(arguments)) //方法1  
  4.   Array.prototype.push.apply(res, arguments)       //方法2  
  5. }  

進制之間的轉換
  1. (int).toString(16); // converts int to hex, eg 12 => "C"  
  2. (int).toString(8); // converts int to octal, eg. 12 => "14"  
  3. parseInt(string,16) // converts hex to int, eg. "FF" => 255  
  4. parseInt(string,8) // converts octal to int, eg. "20" => 16  


將一個數組插入另一個數組指定的位置
  1. var a = [1,2,3,7,8,9];  
  2. var b = [4,5,6];  
  3. var insertIndex = 3;  
  4. a.splice.apply(a, Array.prototype.concat(insertIndex, 0, b));  

刪除數組元素
  1. var a = [1,2,3,4,5];  
  2. a.splice(3,1);      //a = [1,2,3,5]  

大家也許會想爲什麼要用splice而不用delete,因爲用delete將會在數組裏留下一個空洞,而且後面的下標也並沒有遞減。
判斷是否爲IE
  1. var ie = /*@cc_on !@*/false;  
這樣一句簡單的話就可以判斷是否爲ie,太。。。
其實還有更多妙的方法,請看下面
  1. //edit http://www.lai18.com   
  2. // 貌似是最短的,利用IE不支持標準的ECMAscript中數組末逗號忽略的機制  
  3. var ie = !-[1,];  
  4. // 利用了IE的條件註釋  
  5. var ie = /*@cc_on!@*/false;  
  6. // 還是條件註釋  
  7. var ie//@cc_on=1;  
  8. // IE不支持垂直製表符  
  9. var ie = '\v'=='v';  
  10. // 原理同上  
  11. var ie = !+"\v1";  

學到這個瞬間覺得自己弱爆了。
儘量利用原生方法

要找一組數字中的最大數,我們可能會寫一個循環,例如:
  1. var numbers = [3,342,23,22,124];  
  2. var max = 0;  
  3. for(var i=0;i<numbers.length;i++){  
  4.  if(numbers[i] > max){  
  5.   max = numbers[i];  
  6.  }  
  7. }  
  8. alert(max);  

其實利用原生的方法,可以更簡單實現
  1. var numbers = [3,342,23,22,124];  
  2. numbers.sort(function(a,b){return b - a});  
  3. alert(numbers[0]);  

當然最簡潔的方法便是:
  1. Math.max(12,123,3,2,433,4); // returns 433  
當前也可以這樣
[xhtml] view plaincopy
  1. Math.max.apply(Math, [12, 123, 3, 2, 433, 4]) //取最大值  
  2. Math.min.apply(Math, [12, 123, 3, 2, 433, 4]) //取最小值  
生成隨機數
  1. Math.random().toString(16).substring(2);// toString() 函數的參數爲基底,範圍爲2~36。  
  2.     Math.random().toString(36).substring(2);  
不用第三方變量交換兩個變量的值
  1. a=[b, b=a][0];  

事件委派

舉個簡單的例子:html代碼如下
  1. <h2>Great Web resources</h2>  
  2. <ul id="resources">  
  3.  <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>  
  4.  <li><a href="http://sitepoint.com">Sitepoint</a></li>  
  5.  <li><a href="http://alistapart.com">A List Apart</a></li>  
  6.  <li><a href="http://yuiblog.com">YUI Blog</a></li>  
  7.  <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>  
  8.  <li><a href="http://oddlyspecific.com">Oddly specific</a></li>  
  9. </ul>  

js代碼如下:
  1. // Classic event handling example  
  2. (function(){  
  3.  var resources = document.getElementById('resources');  
  4.  var links = resources.getElementsByTagName('a');  
  5.  var all = links.length;  
  6.  for(var i=0;i<all;i++){  
  7.   // Attach a listener to each link  
  8.   links[i].addEventListener('click',handler,false);  
  9.  };  
  10.  function handler(e){  
  11.   var x = e.target; // Get the link that was clicked  
  12.   alert(x);  
  13.   e.preventDefault();  
  14.  };  
  15. })();  

利用事件委派可以寫出更加優雅的:
  1. (function(){  
  2.  var resources = document.getElementById('resources');  
  3.  resources.addEventListener('click',handler,false);  
  4.  function handler(e){  
  5.   var x = e.target; // get the link tha  
  6.   if(x.nodeName.toLowerCase() === 'a'){  
  7.    alert('Event delegation:' + x);  
  8.    e.preventDefault();  
  9.   }  
  10.  };  
  11. })();  

檢測ie版本
  1. var _IE = (function(){  
  2.   var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');  
  3.   while (  
  4.     div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',  
  5.     all[0]  
  6.   );  
  7.   return v > 4 ? v : false ;  
  8. }());  

javaScript版本檢測
你知道你的瀏覽器支持哪一個版本的Javascript嗎?
  1. var JS_ver = [];  
  2. (Number.prototype.toFixed)?JS_ver.push("1.5"):false;  
  3. ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;  
  4. ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;  
  5. ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;  
  6. ("".trimLeft)?JS_ver.push("1.8.1"):false;  
  7. JS_ver.supports = function()  
  8. {  
  9.   if (arguments[0])  
  10.     return (!!~this.join().indexOf(arguments[0] +",") +",");  
  11.   else  
  12.     return (this[this.length-1]);  
  13. }  
  14. alert("Latest Javascript version supported: "+ JS_ver.supports());  
  15. alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));  
判斷屬性是否存在
  1. // BAD: This will cause an error in code when foo is undefined  
  2. if (foo) {  
  3.   doSomething();  
  4. }  
  5. // GOOD: This doesn't cause any errors. However, even when  
  6. // foo is set to NULL or false, the condition validates as true  
  7. if (typeof foo != "undefined") {  
  8.   doSomething();  
  9. }  
  10. // BETTER: This doesn't cause any errors and in addition  
  11. // values NULL or false won't validate as true  
  12. if (window.foo) {  
  13.   doSomething();  
  14. }  
有的情況下,我們有更深的結構和需要更合適的檢查的時候
  1. // UGLY: we have to proof existence of every  
  2. // object before we can be sure property actually exists  
  3. if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {  
  4.   doSomething();  
  5. }  
其實最好的檢測一個屬性是否存在的方法爲:
  1. if("opera" in window){  
  2.   console.log("OPERA");  
  3. }else{  
  4.   console.log("NOT OPERA");  
  5. }  

檢測對象是否爲數組
  1. var obj=[];  
  2. Object.prototype.toString.call(obj)=="[object Array]";  

給函數傳遞對象
  1. function doSomething() {  
  2.   // Leaves the function if nothing is passed  
  3.   if (!arguments[0]) {  
  4.   return false;  
  5.   }  
  6.   var oArgs  = arguments[0]  
  7.   arg0  = oArgs.arg0 || "",  
  8.   arg1  = oArgs.arg1 || "",  
  9.   arg2  = oArgs.arg2 || 0,  
  10.   arg3  = oArgs.arg3 || [],  
  11.   arg4  = oArgs.arg4 || false;  
  12. }  
  13. doSomething({  
  14.   arg1  : "foo",  
  15.   arg2  : 5,  
  16.   arg4  : false  
  17. });  

爲replace方法傳遞一個函數
  1. var sFlop  = "Flop: [Ah] [Ks] [7c]";  
  2. var aValues = {"A":"Ace","K":"King",7:"Seven"};  
  3. var aSuits = {"h":"Hearts","s":"Spades",  
  4. "d":"Diamonds","c":"Clubs"};  
  5. sFlop  = sFlop.replace(/
    \w+
    /gi, function(match) {  
  6.   match  = match.replace(match[2], aSuits[match[2]]);  
  7.   match  = match.replace(match[1], aValues[match[1]] +" of ");  
  8.   return match;  
  9. });  
  10. // string sFlop now contains:  
  11. // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"  
循環中使用標籤
有時候循環當中嵌套循環,你可能想要退出某一層循環,之前總是用一個標誌變量來判斷,現在才知道有更好的方法
  1. outerloop:  
  2. for (var iI=0;iI<5;iI++) {  
  3.   if (somethingIsTrue()) {  
  4.   // Breaks the outer loop iteration  
  5.   break outerloop;  
  6.   }  
  7.   innerloop:  
  8.   for (var iA=0;iA<5;iA++) {  
  9.     if (somethingElseIsTrue()) {  
  10.     // Breaks the inner loop iteration  
  11.     break innerloop;  
  12.   }  
  13.   }  
  14. }  
對數組進行去重
  1. /* 
  2. *@desc:對數組進行去重操作,返回一個沒有重複元素的新數組 
  3. */  
  4. function unique(target) {  
  5.   var result = [];  
  6.   loop: for (var i = 0, n = target.length; i < n; i++) {  
  7.     for (var x = i + 1; x < n; x++) {  
  8.       if (target[x] === target[i]) {  
  9.         continue loop;  
  10.       }  
  11.     }  
  12.     result.push(target[i]);  
  13.   }  
  14.   return result;  
  15. }  

或者如下:
  1. Array.prototype.distinct = function () {  
  2.   var newArr = [],obj = {};  
  3.   for(var i=0, len = this.length; i < len; i++){  
  4.     if(!obj[typeof(this[i]) + this[i]]){  
  5.       newArr.push(this[i]);  
  6.       obj[typeof(this[i]) + this[i]] = 'new';  
  7.     }  
  8.   }  
  9.   return newArr;  
  10. }  

其實最優的方法是這樣的
  1. Array.prototype.distinct = function () {   
  2.   var sameObj = function(a, b){   
  3.     var tag = true;   
  4.     if(!a || !b) return false;   
  5.     for(var x in a){   
  6.       if(!b[x]) return false;   
  7.       if(typeof(a[x]) === 'object'){   
  8.         tag = sameObj(a[x],b[x]);   
  9.       } else {   
  10.         if(a[x]!==b[x])   
  11.         return false;   
  12.       }   
  13.     }   
  14.     return tag;   
  15.   }   
  16.   var newArr = [], obj = {};   
  17.   for(var i = 0, len = this.length; i < len; i++){   
  18.     if(!sameObj(obj[typeof(this[i]) + this[i]], this[i])){   
  19.     newArr.push(this[i]);   
  20.     obj[typeof(this[i]) + this[i]] = this[i];   
  21.     }   
  22.   }   
  23.   return newArr;   
  24. }  

使用範例(借用評論):
  1. var arr=[{name:"tom",age:12},{name:"lily",age:22},{name:"lilei",age:12}];  
  2. var newArr=arr.distinct(function(ele){  
  3.  return ele.age;  
  4. });  

查找字符串中出現最多的字符及個數
  1. var i, len, maxobj='', maxnum=0, obj={};  
  2. var arr = "sdjksfssscfssdd";  
  3. for(i = 0, len = arr.length; i < len; i++){  
  4.   obj[arr[i]] ? obj[arr[i]]++ : obj[arr[i]] = 1;  
  5.   if(maxnum < obj[arr[i]]){  
  6.     maxnum = obj[arr[i]];  
  7.     maxobj = arr[i];  
  8.   }  
  9. }  
  10. alert(maxobj + "在數組中出現了" + maxnum + "次");  

其實還有很多,這些只是我閒來無事總結的一些罷了。 

轉載自http://blog.csdn.net/hello_katty/article/details/46452999

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章