javascrit 常用

大家都知道,全世界來說JavaScript是超流行的編程語言之一,開發者用它不僅可以開發出炫麗的Web程序,還可以用它來開發一些移動應用程序(如 PhoneGap或Appcelerator),甚至是服務端應用,比如NodeJS、Wakanda以及其它實現。此外,許多開發者都會把 JavaScript選爲入門語言,使用它來做一些基本的彈出窗口等。

在本篇文章中,我們將會向大家分享JavaScript開發中的小技巧、最佳實踐和實用內容,不管你是前端開發者還是服務端開發者,都應該來看看這些編程的技巧總結,絕對會讓你受益匪淺的。

文中所提供的代碼片段都已經過最新版的Chrome 30測試,該瀏覽器使用V8 JavaScript引擎(V8 3.20.17.15)。

1.第一次給變量賦值時,別忘記var關鍵字

如果初次賦值給未聲明的變量,該變量會被自動創建爲全局變量,在JS開發中,應該避免使用全局變量,這是大家容易忽略的錯誤。

2.使用===而非==

並且永遠不要使用=或!=。

[10] === 10    // is false  
[10]  == 10    // is true  
'10' == 10     // is true  
'10' === 10    // is false  
 []   == 0     // is true  
 [] ===  0     // is false  
 '' == false   // is true but true == "a" is false  
 '' ===   false // is false  

3.使用分號來作爲行終止字符

在行終止的地方使用分號是一個很好的習慣,即使開發人員忘記加分號,編譯器也不會有任何提示,因爲在大多數情況下,JavaScript解析器會自動加上。

    function Person(firstName, lastName){  
        this.firstName =  firstName;  
        this.lastName = lastName;          
    }    
      
    var Saad = new Person("Saad", "Mousliki");  

5.小心使用typeof、instanceof和constructor

var arr = ["a", "b", "c"];  
typeof arr;   // return "object"   
arr  instanceof Array // true  
arr.constructor();  //[]

6.創建一個自調用(Self-calling)函數

通常被稱爲自調用匿名函數或即刻調用函數表達式(LLFE)。當函數被創建的時候就會自動執行,如下:

    (function(){  
        // some private code that will be executed automatically  
    })();    
    (function(a,b){  
        var result = a+b;  
        return result;  
    })(10,20)  

7.給數組創建一個隨機項

    var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];  
      
    var  randomItem = items[Math.floor(Math.random() * items.length)];  

8.在特定範圍裏獲得一個隨機數

下面這段代碼非常通用,當你需要生成一個測試的數據時,比如在最高工資和最低工資之間獲取一個隨機數的話。

    var x = Math.floor(Math.random() * (max - min + 1)) + min;  

9.在數字0和最大數之間生成一組隨機數

    var numbersArray = [] , max = 100;  
      
    for( var i=1; numbersArray.push(i++) < max;);  // numbers = [0,1,2,3 ... 100]   

10.生成一組隨機的字母數字字符

    function generateRandomAlphaNum(len) {  
        var rdmstring = "";  
        for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));  
        return  rdmString.substr(0, len);  
      
    }  

11.打亂數字數組

    var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];  
    numbers = numbers.sort(function(){ return Math.random() - 0.5});  
    /* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205]  */  

12.字符串trim函數

trim函數可以刪除字符串兩端的空白字符,可以用在Java、C#、PHP等多門語言裏。

    String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};    

13.數組追加

    var array1 = [12 , "foo" , {name "Joe"} , -2458];  
      
    var array2 = ["Doe" , 555 , 100];  
    Array.prototype.push.apply(array1, array2);  
    /* array1 will be equal to  [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */  

14.將參數對象轉換爲數組

    var argArray = Array.prototype.slice.call(arguments);  

15.驗證一個指定參數是否爲數字

    function isNumber(n){  
        return !isNaN(parseFloat(n)) && isFinite(n);  
    }  

16.驗證一個給定的參數爲數組

    function isArray(obj){  
        return Object.prototype.toString.call(obj) === '[object Array]' ;  
    }  

注意,如果toString()方法被重寫了,你將不會得到預期結果。

或者你可以這樣寫:

    Array.isArray(obj); // its a new Array method  

同樣,如果你使用多個frames,你可以使用instancesof,如果內容太多,結果同樣會出錯。

    var myFrame = document.createElement('iframe');  
    document.body.appendChild(myFrame);  
      
    var myArray = window.frames[window.frames.length-1].Array;  
    var arr = new myArray(a,b,10); // [a,b,10]    
      
    // instanceof will not work correctly, myArray loses his constructor   
    // constructor is not shared between frames  
    arr instanceof Array; // false  

17.從數字數組中獲得最大值和最小值

    var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];   
    var maxInNumbers = Math.max.apply(Math, numbers);   
    var minInNumbers = Math.min.apply(Math, numbers);  

18.清空數組

    var myArray = [12 , 222 , 1000 ];    
    myArray.length = 0; // myArray will be equal to [].  

19.不要用delete從數組中刪除項目

開發者可以使用split來替代delete去刪除數組中的項目。好的方式是使用delete去替換數組中undefined的數組項目,而不是使用delete去刪除數組中項目。

    var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];   
    items.length; // return 11   
    delete items[3]; // return true   
    items.length; // return 11   
    /* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */  

應該如下使用

    var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];   
    items.length; // return 11   
    items.splice(3,1) ;   
    items.length; // return 10   
    /* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */  

delete方法應該用來刪除一個對象屬性。

20.使用length屬性截短數組

如上文提到的清空數組,開發者還可以使用length屬性截短數組。

    var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];    
    myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].  

如果你所定義的數組長度值過高,那麼數組的長度將會改變,並且會填充一些未定義的值到數組裏,數組的length屬性不是隻讀的。

    myArray.length = 10; // the new array length is 10   
    myArray[myArray.length - 1] ; // undefined  


繼續上一部分,這裏是45個JavaScript技巧和最佳實踐的第二部分,如果你沒有閱讀第一篇的話,請在這裏閱讀:

45個超實用的JavaScript技巧及最佳實踐(一)

21. 使用邏輯AND/OR來處理條件語句

  1. var foo = 10;
  2. foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
  3. foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();

邏輯AND也可以用來設置含糊參數缺省的值

  1. Function doSomething(arg1){
  2. Arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set
  3. }

22. 使用map()函數方法來循環數組裏的項目

  1. var squares = [1,2,3,4].map(function (val) {
  2. return val * val;
  3. });
  4. // squares will be equal to [1, 4, 9, 16]

23. 按小數點後N位來四捨五入

  1. var num =2.443242342;
  2. num = num.toFixed(4); // num will be equal to 2.4432

24. 浮點問題

  1. 0.1 + 0.2 === 0.3 // is false
  2. 9007199254740992 + 1 // is equal to 9007199254740992
  3. 9007199254740992 + 2 // is equal to 9007199254740994

爲什麼? 0.1 + 0.2 等於 0.30000000000000004 。你應該知道所有的javascript數字在64位2進制內部都是使用浮點表示

這個來自於IEEE 754標準。更多信息介紹,請參考:相關博客

你可以使用上面介紹的toFixed()和toPrecision()來解決這個問題

25. 使用for-in循環來檢查對象的指定屬性

下面的代碼片段非常實用,可以避免從對象的prototype來循環遍歷對象的屬性:

  1. for (var name in object) {
  2. if (object.hasOwnProperty(name)) {
  3. // do something with name
  4. }
  5. }

26. 逗號操作符

  1. var a = 0;
  2. var b = ( a++, 99 );
  3. console.log(a); // a will be equal to 1
  4. console.log(b); // b is equal to 99

27. 緩存需要計算或者DOM查詢的變量

使用jQuery的選擇器,我們一定要記住緩存DOM元素,這樣會提高執行效率:

  1. var navright = document.querySelector('#right');
  2. var navleft = document.querySelector('#left');
  3. var navup = document.querySelector('#up');
  4. var navdown = document.querySelector('#down');

28. 在傳入isFinite()之前驗證參數

  1. isFinite(0/0) ; // false
  2. isFinite("foo"); // false
  3. isFinite("10"); // true
  4. isFinite(10); // true
  5. isFinite(undifined); // false
  6. isFinite(); // false
  7. isFinite(null); // true !!!

 29. 避免數組中index爲負值

  1. var numbersArray = [1,2,3,4,5];
  2. var from = numbersArray.indexOf("foo") ; // from is equal to -1
  3. numbersArray.splice(from,2); // will return [5]

這裏需要注意indexof的參數 不能爲負值,但是splice可以

30. 序列化和反序列化(用來處理JSON)

  1. var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
  2. var stringFromPerson = JSON.stringify(person);
  3. /* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
  4. var personFromString = JSON.parse(stringFromPerson);
  5. /* personFromString is equal to person object */

31. 避免使用eval或者Function構建器

使用eval或者function構建器是一件非常消耗資源的操作,因爲每次調用script引擎都必須將源代碼轉換爲可執行的代碼

  1. var func1 = new Function(functionCode); //避免使用!!
  2. var func2 = eval(functionCode);//避免使用!!

32. 避免使用with()

使用with()可以用來插入一個變量到全局。然而,如果另外一個變量擁有同樣的名字,將會導致非常混亂並且會覆蓋數值

33. 避免在數組中使用for-in循環

不推薦使用:

  1. var sum = 0;
  2. for (var i in arrayNumbers) {
  3. sum += arrayNumbers[i];
  4. }

如下代碼將會更好:

  1. var sum = 0;
  2. for (var i = 0, len = arrayNumbers.length; i < len; i++) {
  3. sum += arrayNumbers[i];
  4. }

作爲額外的好處,i和len的實例化都執行一次,因爲都是循環中的第一個語句,但是比下面執行速度更快:

  1. for (var i = 0; i < arrayNumbers.length; i++)

爲什麼? arrayNumbers的長度在每次循環都計算一次

34. 傳遞函數,而非字符串到setTimeout()和setInterval()中

如果你傳遞一個字符串到setTimeout和setInterval中,處理方式和eval將會類似,速度會很慢,不要使用如下:

  1. setInterval('doSomethingPeriodically()', 1000);
  2. setTimeOut('doSomethingAfterFiveSeconds()', 5000);

推薦使用如下

  1. setInterval(doSomethingPeriodically, 1000);
  2. setTimeOut(doSomethingAfterFiveSeconds, 5000);

35. 使用switch/case語句而非一系列的if/else

如果多餘兩個條件,使用switch/case將會更快,而且語法更優雅(代碼組織的更好)。對於多餘10個條件的避免使用。

36. 使用switch/case語句處理數值區域

使用如下小技巧處理數值區域:

  1. function getCategory(age) {
  2. var category = "";
  3. switch (true) {
  4. case isNaN(age):
  5. category = "not an age";
  6. break;
  7. case (age >= 50):
  8. category = "Old";
  9. break;
  10. case (age <= 20):
  11. category = "Baby";
  12. break;
  13. default:
  14. category = "Young";
  15. break;
  16. };
  17. return category;
  18. }
  19. getCategory(5); // will return "Baby"

37. 創建一個prototype是指定對象的對象

使用如下代碼可以生成一個prototype是指定對象的對象:

  1. function clone(object) {
  2. function OneShotConstructor(){};
  3. OneShotConstructor.prototype= object;
  4. return new OneShotConstructor();
  5. }
  6. clone(Array).prototype ; // []

39. 一個HTMLescaper方法

  1. function escapeHTML(text) {
  2. var replacements= {"<": "&lt;", ">": "&gt;","&": "&amp;", "\"": "&quot;"};
  3. return text.replace(/[<>&"]/g, function(character) {
  4. return replacements[character];
  5. });
  6. }

編譯:當然,前臺處理並不安全,後臺處理更徹底

40. 在循環中避免使用try-catch-finally

不要使用如下代碼:

  1. var object = ['foo', 'bar'], i;
  2. for (i = 0, len = object.length; i <len; i++) {
  3. try {
  4. // do something that throws an exception
  5. }
  6. catch (e) {
  7. // handle exception
  8. }
  9. }

使用這段代碼:

  1. var object = ['foo', 'bar'], i;
  2. try {
  3. for (i = 0, len = object.length; i <len; i++) {
  4. // do something that throws an exception
  5. }
  6. }
  7. catch (e) {
  8. // handle exception
  9. }

40. 設置XMLHttpRequests的timeout

如果一個XHR花費了太多時間,你可以在XHR調用中使用setTimeout來退出連接:

  1. var xhr = new XMLHttpRequest ();
  2. xhr.onreadystatechange = function () {
  3. if (this.readyState == 4) {
  4. clearTimeout(timeout);
  5. // do something with response data
  6. }
  7. }
  8. var timeout = setTimeout( function () {
  9. xhr.abort(); // call error callback
  10. }, 60*1000 /* timeout after a minute */ );
  11. xhr.open('GET', url, true);
  12.  
  13. xhr.send();

額外的好處,你可以完全避免同步AJAX調用

41. 處理WebSocket timeout

一般來說,當一個websocket連接建立後,服務器可以在30秒無響應的情況下time out你的連接。防火牆也可以做到。

爲了處理timeout問題,你可以定時發送一個空的消息到服務器。爲了實現,你可以添加兩個方法到你的代碼中:

一個保證連接的存在,另外一個取消連接。使用這個技巧,你可以處理timeout問題:

  1. var timerID = 0;
  2. function keepAlive() {
  3. var timeout = 15000;
  4. if (webSocket.readyState == webSocket.OPEN) {
  5. webSocket.send('');
  6. }
  7. timerId = setTimeout(keepAlive, timeout);
  8. }
  9. function cancelKeepAlive() {
  10. if (timerId) {
  11. cancelTimeout(timerId);
  12. }
  13. }

keepAlive函數可以添加到webSocket的onOpen函數的最後。cancelKeepAlive添加到webSocket的onClose函數最後。

42. 記住,操作符比函數調用更快

不推薦使用:

  1. var min = Math.min(a,b);
  2. A.push(v);

推薦使用:

  1. var min = a < b ? a:b;
  2. A[A.length] = v;

43. 不要忘記使用代碼美化工具。在代碼產品化前使用JSLint和代碼壓縮工具(例如,JSMin)來處理

44. Javascript是超棒的語言:更多資源請點擊這裏

轉自http://www.gbtags.com/gb/share/2681.htm
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章