JavaScript技巧及最佳实践

来源:互联网 发布:怎么改淘宝评价用手机 编辑:程序博客网 时间:2024/05/17 23:14

大家都知道,全世界来说JavaScript是超流行的编程语言之一,开发者用它不仅可以开发出炫丽的Web程序,还可以用它来开发一些移动应用程序(如PhoneGapAppcelerator),甚至是服务端应用,比如NodeJSWakanda以及其它实现。此外,许多开发者都会把 JavaScript选为入门语言,使用它来做一些基本的弹出窗口等。

在本篇文章中,我们将会向大家分享JavaScript开发中的小技巧、最佳实践和实用内容,不管你是前端开发者还是服务端开发者,都应该来看看这些编程的技巧总结,绝对会让你受益匪浅的。

文中所提供的代码片段都已经过最新版的Chrome30测试,该浏览器使用V8JavaScript引擎(V83.20.17.15)。

1.第一次给变量赋值时,别忘记var关键字

如果初次赋值给未声明的变量,该变量会被自动创建为全局变量,在JS开发中,应该避免使用全局变量,这是大家容易忽略的错误。

2.使用===而非==

并且永远不要使用=或!=

1.    [10] === 10    // is false  
2.    [10]  == 10    // is true  
3.    '10' == 10     // is true  
4.    '10' === 10    // is false  
5.     []   == 0     // is true  
6.     [] ===  0     // is false  
7.     '' == false   // is true but true == "a" is false  
8.     '' ===   false // is false  

3.使用分号来作为行终止字符

在行终止的地方使用分号是一个很好的习惯,即使开发人员忘记加分号,编译器也不会有任何提示,因为在大多数情况下,JavaScript解析器会自动加上。

1.        function Person(firstName, lastName){  
2.            this.firstName =  firstName;  
3.            this.lastName = lastName;          
4.        }    
5.          
6.        var Saad = new Person("Saad", "Mousliki");  

5.小心使用typeof、instanceof和constructor

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

6.创建一个自调用(Self-calling)函数

通常被称为自调用匿名函数或即刻调用函数表达式(LLFE)。当函数被创建的时候就会自动执行,如下:

1.        (function(){  
2.            // some private code that will be executed automatically  
3.        })();    
4.        (function(a,b){  
5.            var result = a+b;  
6.            return result;  
7.        })(10,20)  

7.给数组创建一个随机项

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

8.在特定范围里获得一个随机数

下面这段代码非常通用,当你需要生成一个测试的数据时,比如在最高工资和最低工资之间获取一个随机数的话。

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

9.在数字0和最大数之间生成一组随机数

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

10.生成一组随机的字母数字字符

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

11.打乱数字数组

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

12.字符串trim函数

trim函数可以删除字符串两端的空白字符,可以用在JavaC#PHP等多门语言里。

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

13.数组追加

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

14.将参数对象转换为数组

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

15.验证一个指定参数是否为数字

1.        function isNumber(n){  
2.            return !isNaN(parseFloat(n)) && isFinite(n);  
3.        }  

16.验证一个给定的参数为数组

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

注意,如果toString()方法被重写了,你将不会得到预期结果。

或者你可以这样写:

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

同样,如果你使用多个frames,你可以使用instancesof,如果内容太多,结果同样会出错。

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

17.从数字数组中获得最大值和最小值

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

18.清空数组

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

19.不要用delete从数组中删除项目

开发者可以使用split来替代delete去删除数组中的项目。好的方式是使用delete去替换数组中undefined的数组项目,而不是使用delete去删除数组中项目。

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

应该如下使用

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

delete方法应该用来删除一个对象属性。

20.使用length属性截短数组

如上文提到的清空数组,开发者还可以使用length属性截短数组。

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

如果你所定义的数组长度值过高,那么数组的长度将会改变,并且会填充一些未定义的值到数组里,数组的length属性不是只读的。

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

 

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数字在642进制内部都是使用浮点表示

这个来自于IEEE754标准。更多信息介绍,请参考:相关博客

你可以使用上面介绍的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.    }

作为额外的好处,ilen的实例化都执行一次,因为都是循环中的第一个语句,但是比下面执行速度更快:

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

为什么?arrayNumbers的长度在每次循环都计算一次

34. 传递函数,而非字符串到setTimeout()和setInterval()中

如果你传递一个字符串到setTimeoutsetInterval中,处理方式和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. 处理WebSockettimeout

一般来说,当一个websocket连接建立后,服务器可以在30秒无响应的情况下timeout你的连接。防火墙也可以做到。

为了处理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函数可以添加到webSocketonOpen函数的最后。cancelKeepAlive添加到webSocketonClose函数最后。

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)来处理

 

0 0