超实用的JavaScript技巧及最佳实践(下)

在前段时间,CSDN研发频道发表了超实用的JavaScript技巧及最佳实践(上),很多开发者都觉得里面所提到的技巧非常实用,基于此,我们再向大家推荐超实用的JavaScript技巧及最佳实践(下),希望对大家有所帮助。
文中所提供的代码片段都已经过最新版的Chrome 30测试,该浏览器使用V8 JavaScript引擎(V8 3.20.17.15)。
1.使用逻辑符号&&或者||进行条件判断

  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();    
var foo = 10;    
foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();   
foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();  
  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]     
var squares = [1,2,3,4].map(function (val) {    
    return val * val;    
});   
// squares will be equal to [1, 4, 9, 16]   
AND也可以用来设置函数参数的默认值
  1. Function doSomething(arg1){     
  2.     Arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set    
  3. }    
Function doSomething(arg1){   
    Arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set  
}  
2.使用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]     
var squares = [1,2,3,4].map(function (val) {    
    return val * val;    
});   
// squares will be equal to [1, 4, 9, 16]   
3.舍入小数位数
  1. var num =2.443242342;    
  2. num = num.toFixed(4);  // num will be equal to 2.4432    
var num =2.443242342;  
num = num.toFixed(4);  // num will be equal to 2.4432  
4.浮点数问题
  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.3 // is false   
9007199254740992 + 1 // is equal to 9007199254740992    
9007199254740992 + 2 // is equal to 9007199254740994  

0.1+0.2等于0.30000000000000004,为什么会发生这种情况?根据IEEE754标准,你需要知道的是所有JavaScript数字在64位二进制内的都表示浮点数。开发者可以使用toFixed()和toPrecision()方法来解决这个问题。
5.使用for-in loop检查遍历对象属性 下面这段代码主要是为了避免遍历对象属性。
  1. for (var name in object) {      
  2.     if (object.hasOwnProperty(name)) {     
  3.         // do something with name                        
  4.     }      
  5. }    
for (var name in object) {    
    if (object.hasOwnProperty(name)) {   
        // do something with name                      
    }    
}  
6.逗号操作符
  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     
var a = 0;   
var b = ( a++, 99 );   
console.log(a);  // a will be equal to 1   
console.log(b);  // b is equal to 99   
7.计算或查询缓存变量 在使用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');    
var navright = document.querySelector('#right');   
var navleft = document.querySelector('#left');   
var navup = document.querySelector('#up');   
var navdown = document.querySelector('#down');  
8.在将参数传递到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  !!!   
isFinite(0/0) ; // false   
isFinite("foo"); // false   
isFinite("10"); // true   
isFinite(10);   // true   
isFinite(undifined);  // false   
isFinite();   // false   
isFinite(null);  // true  !!! 
9.在数组中避免负向索引
  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]    
var numbersArray = [1,2,3,4,5];   
var from = numbersArray.indexOf("foo") ;  // from is equal to -1   
numbersArray.splice(from,2);    // will return [5]  
确保参数传递到indexOf()方法里是非负向的。
10.(使用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  */    
var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };   
var stringFromPerson = JSON.stringify(person);   
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}"   */   
var personFromString = JSON.parse(stringFromPerson);    
/* personFromString is equal to person object  */  
11.避免使用eval()或Function构造函数 eval()和Function构造函数被称为脚本引擎,每次执行它们的时候都必须把源码转换成可执行的代码,这是非常昂过的操作。
  1. var func1 = new Function(functionCode);    
var func1 = new Function(functionCode);  
12.避免使用with()方法 如果在全局区域里使用with()插入变量,那么,万一有一个变量名字和它名字一样,就很容易混淆和重写。
13.避免在数组里使用for-in loop
  1. //而不是这样用:  
  2. var sum = 0;      
  3. for (var i in arrayNumbers) {      
  4.     sum += arrayNumbers[i];      
  5. }    
  6.   
  7. //这样会更好:  
  8. var sum = 0;      
  9. for (var i = 0, len = arrayNumbers.length; i < len; i++) {      
  10.     sum += arrayNumbers[i];      
  11. }    
  12.   
  13. //这样会更快:  
  14. for (var i = 0; i < arrayNumbers.length; i++)   
//而不是这样用:
var sum = 0;    
for (var i in arrayNumbers) {    
    sum += arrayNumbers[i];    
}  

//这样会更好:
var sum = 0;    
for (var i = 0, len = arrayNumbers.length; i < len; i++) {    
    sum += arrayNumbers[i];    
}  

//这样会更快:
for (var i = 0; i < arrayNumbers.length; i++) 
为什么?数组长度arraynNumbers在每次loop迭代时都会被重新计算。
14.不要向setTimeout()和setInterval()方法里传递字符串 如果在这两个方法里传递字符串,那么字符串会像eval那样重新计算,这样速度就会变慢,
  1. //而不是这样使用:  
  2. setInterval('doSomethingPeriodically()', 1000);      
  3. setTimeOut('doSomethingAfterFiveSeconds()', 5000);    
  4.   
  5. //相反,应该这样用:  
  6. setInterval(doSomethingPeriodically, 1000);      
  7. setTimeOut(doSomethingAfterFiveSeconds, 5000);   
//而不是这样使用:
setInterval('doSomethingPeriodically()', 1000);    
setTimeOut('doSomethingAfterFiveSeconds()', 5000);  

//相反,应该这样用:
setInterval(doSomethingPeriodically, 1000);    
setTimeOut(doSomethingAfterFiveSeconds, 5000); 
15.使用switch/case语句代替较长的if/else语句 如果有超过2个以上的case,那么使用switch/case速度会快很多,而且代码看起来更加优雅。
16.遇到数值范围时,可以选用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"   
function getCategory(age) {    
    var category = "";    
    switch (true) {    
        case isNaN(age):    
            category = "not an age";    
            break;    
        case (age >= 50):    
            category = "Old";    
            break;    
        case (age <= 20):    
            category = "Baby";    
            break;    
        default:    
            category = "Young";    
            break;    
    };    
    return category;    
}    
getCategory(5);  // will return "Baby" 
17.创建一个对象,该对象的属性是一个给定的对象 可以编写一个这样的函数,创建一个对象,该对象属性是一个给定的对象,好比这样:
  1. function clone(object) {      
  2.     function OneShotConstructor(){};     
  3.     OneShotConstructor.prototype= object;      
  4.     return new OneShotConstructor();     
  5. }     
  6. clone(Array).prototype ;  // []   
function clone(object) {    
    function OneShotConstructor(){};   
    OneShotConstructor.prototype= object;    
    return new OneShotConstructor();   
}   
clone(Array).prototype ;  // [] 
18.一个HTML escaper函数
  1. function escapeHTML(text) {      
  2.     var replacements= {"<": "<", ">": ">","&": "&", "\"": """};                          
  3.     return text.replace(/[<>&"]/g, function(character) {      
  4.         return replacements[character];      
  5.     });     
  6. }  
function escapeHTML(text) {    
    var replacements= {"<": "<", ">": ">","&": "&", "\"": """};                        
    return text.replace(/[<>&"]/g, function(character) {    
        return replacements[character];    
    });   
}
19.在一个loop里避免使用try-catch-finally try-catch-finally在当前范围里运行时会创建一个新的变量,在执行catch时,捕获异常对象会赋值给变量。 
  1. //不要这样使用:  
  2. var object = ['foo', 'bar'], i;      
  3. for (i = 0, len = object.length; i < len; i++) {      
  4.     try {      
  5.         // do something that throws an exception     
  6.     }      
  7.     catch (e) {       
  8.         // handle exception      
  9.     }     
  10. }    
  11.   
  12. //应该这样使用:  
  13. var object = ['foo', 'bar'], i;      
  14. try {     
  15.     for (i = 0, len = object.length; i < len; i++) {      
  16.         // do something that throws an exception     
  17.     }     
  18. }     
  19. catch (e) {       
  20.     // handle exception      
  21. }   
//不要这样使用:
var object = ['foo', 'bar'], i;    
for (i = 0, len = object.length; i < len; i++) {    
    try {    
        // do something that throws an exception   
    }    
    catch (e) {     
        // handle exception    
    }   
}  

//应该这样使用:
var object = ['foo', 'bar'], i;    
try {   
    for (i = 0, len = object.length; i < len; i++) {    
        // do something that throws an exception   
    }   
}   
catch (e) {     
    // handle exception    
} 
20.给XMLHttpRequests设置timeouts  如果一个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. xhr.send();   
var xhr = new XMLHttpRequest ();   
xhr.onreadystatechange = function () {    
    if (this.readyState == 4) {    
        clearTimeout(timeout);    
        // do something with response data   
    }    
}    
var timeout = setTimeout( function () {    
    xhr.abort(); // call error callback    
}, 60*1000 /* timeout after a minute */ );   
xhr.open('GET', url, true);      
xhr.send(); 
此外,通常你应该完全避免同步Ajax调用。
21.处理WebSocket超时 一般来说,当创建一个WebSocket链接时,服务器可能在闲置30秒后链接超时,在闲置一段时间后,防火墙也可能会链接超时。  为了解决这种超时问题,你可以定期地向服务器发送空信息,在代码里添加两个函数:一个函数用来保持链接一直是活的,另一个用来取消链接是活的,使用这种方法,你将控制超时问题。  添加一个timeId……
  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. }   
var timerId = 0;   
function keepAlive() {   
    var timeout = 15000;    
    if (webSocket.readyState == webSocket.OPEN) {    
        webSocket.send('');    
    }    
    timerId = setTimeout(keepAlive, timeout);    
}    
function cancelKeepAlive() {    
    if (timerId) {    
        cancelTimeout(timerId);    
    }    
} 
keepAlive()方法应该添加在WebSocket链接方法onOpen()的末端,cancelKeepAlive()方法放在onClose()方法下面。 
22.记住,最原始的操作要比函数调用快 对于简单的任务,最好使用基本操作方式来实现,而不是使用函数调用实现。 
  1. //例如  
  2. var min = Math.min(a,b);     
  3. A.push(v);    
  4.   
  5. //基本操作方式:  
  6. var min = a < b ? a b;     
  7. A[A.length] = v;     
//例如
var min = Math.min(a,b);   
A.push(v);  

//基本操作方式:
var min = a < b ? a b;   
A[A.length] = v;   
23.编码时注意代码的美观、可读 JavaScript是一门非常好的语言,尤其对于前端工程师来说,JavaScript也非常重要,点击这里[http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript]可以访问更多优秀的JavaScript资源。

 

 

24. 不要忘记使用代码美化工具。在代码产品化前使用JSLint和代码压缩工具(例如,JSMin)来处理

posted @ 2014-11-11 14:36  x_window  阅读(142)  评论(0)    收藏  举报