---
title: "超实用的JavaScript技巧及最佳实践"
author: "weistar"
date: "2014-01-08T17:17:55Z"
tags: []
categories: ["编程语言"]
slug: "javascript"
draft: true
lastmod: "2014-01-08T17:21:58Z"
id: 2001415
url: "https://weistar.iteye.com/blog/2001415"
---

**1.****使用逻辑符号&&或者||进行条件判断**

```
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();
```

 AND也可以用来设置函数参数的默认值

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

 **2.使用map()方法来遍历数组**

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

**3.舍入小数位数** 

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

 **4.浮点数问题**

```
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检查遍历对象属性**

下面这段代码主要是为了避免遍历对象属性。

```
for (var name in object) {  
    if (object.hasOwnProperty(name)) { 
        // do something with name                    
    }  
}
```

 **6.逗号操作符**

```
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元素

```
var navright = document.querySelector('#right'); 
var navleft = document.querySelector('#left'); 
var navup = document.querySelector('#up'); 
var navdown = document.querySelector('#down');
```

 **8.在将参数传递到isFinite()之前进行验证**

```
isFinite(0/0) ; // false 
isFinite("foo"); // false 
isFinite("10"); // true 
isFinite(10);   // true 
isFinite(undifined);  // false 
isFinite();   // false 
isFinite(null);  // true  !!! 
```

 **9.在数组中避免负向索引**

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

**10.（使用JSON）序列化和反序列化**

```
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构造函数被称为脚本引擎，每次执行它们的时候都必须把源码转换成可执行的代码，这是非常昂过的操作。

```
var func1 = new Function(functionCode);
var func2 = eval(functionCode);
```

**12.避免使用with()方法**

如果在全局区域里使用with()插入变量，那么，万一有一个变量名字和它名字一样，就很容易混淆和重写。

**13.避免在数组里使用for-in loop**

而不是这样用：

```
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那样重新计算，这样速度就会变慢，而不是这样使用：

```
setInterval('doSomethingPeriodically()', 1000);  
setTimeOut('doSomethingAfterFiveSeconds()', 5000);
```

 相反，应该这样用：

```
setInterval(doSomethingPeriodically, 1000);  
setTimeOut(doSomethingAfterFiveSeconds, 5000);
```

**15.使用switch/case语句代替较长的if/else语句**

 如果有超过2个以上的case，那么使用switch/case速度会快很多，而且代码看起来更加优雅。

**16.遇到数值范围时，可以选用switch/casne**

```
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.创建一个对象，该对象的属性是一个给定的对象**

 可以编写一个这样的函数，创建一个对象，该对象属性是一个给定的对象，好比这样

```
function clone(object) {  
    function OneShotConstructor(){}; 
    OneShotConstructor.prototype= object;  
    return new OneShotConstructor(); 
} 
clone(Array).prototype ;  // []
```

 **18.一个HTML escaper函数**

```
function escapeHTML(text) {  
    var replacements= {"<": "<", ">": ">","&": "&", "\"": """};                      
    return text.replace(/[<>&"]/g, function(character) {  
        return replacements[character];  
    }); 
}
```

 **19.在一个loop里避免使用try-catch-finally**

try-catch-finally在当前范围里运行时会创建一个新的变量，在执行catch时，捕获异常对象会赋值给变量。

不要这样使用：

```
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()解决。

```
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……

```
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.记住，最原始的操作要比函数调用快**

对于简单的任务，最好使用基本操作方式来实现，而不是使用函数调用实现。

例如

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

 基本操作方式：

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

 **23. – Don’t forget `var` keyword when assigning a variable’s value for the first time.**

 

 **24. – use `===` instead of `==`**

```
[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 
```

 **25. – `undefined`, `null`, 0, `false`, `NaN`, `''` (empty string) are all false.**

 

 **26. – Create a Self-calling Function**

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

 **27. – A string trim function**

The classic trim function of Java, C#, PHP and many other language that remove whitespace from a string doesn’t exist in JavaScript, so we could add it to the `String` object.

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

 **28. – Append an array to another array**

```
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] */
```

 **29. – Transform the `arguments` object into an array**

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

 **30. – Verify that a given argument is a number**

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

 **31. – Verify that a given argument is an array**

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

 Note that if the toString() method is overridden, you will not get the expected result using this trick.

Or use…

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

 You could also use `instanceof` if you are not working with multiple frames. However, if you have many contexts, you will get a wrong result.

```
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
```

 **32. – Get the max or the min in an array of numbers**

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

 **33. – Empty an array**

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

 **34. – Don’t use delete to remove an item from array**

Use `split` instead of using `delete` to delete an item from an array. Using `delete` replaces the item with `undefined` instead of the removing it from the array.

Instead of… &gt;

```
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]   */
```

 Use…

```
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]   */
```

 The delete method should be used to delete an object property.

 **35. – Truncate an array using length**

Like the previous example of emptying an array, we truncate it using the `length` property.

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