javascript技巧

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

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

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

Function doSomething(arg1){   
  1.     Arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set  
  2. }  
2.使用map()方法来遍历数组

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

var num =2.443242342;  
  1. num = num.toFixed(4);  // num will be equal to 2.4432  
4.浮点数问题

0.1 + 0.2 === 0.3 // is false   

  1. 9007199254740992 + 1 // is equal to 9007199254740992    
  2. 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) {    
  1.     if (object.hasOwnProperty(name)) {   
  2.         // do something with name                      
  3.     }    
  4. }  
6.逗号操作符

var a = 0;   
  1. var b = ( a++, 99 );   
  2. console.log(a);  // a will be equal to 1   
  3. console.log(b);  // b is equal to 99  
7.计算或查询缓存变量

在使用jQuery选择器的情况下,开发者可以缓存DOM元素

var navright = document.querySelector('#right');   
  1. var navleft = document.querySelector('#left');   
  2. var navup = document.querySelector('#up');   
  3. var navdown = document.querySelector('#down');  
8.在将参数传递到isFinite()之前进行验证

isFinite(0/0) ; // false   
  1. isFinite("foo"); // false   
  2. isFinite("10"); // true   
  3. isFinite(10);   // true    
  4. isFinite(undifined);  // false   
  5. isFinite();   // false    
  6. isFinite(null);  // true  !!!   
9.在数组中避免负向索引

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

确保参数传递到indexOf()方法里是非负向的。

10.(使用JSON)序列化和反序列化

var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };   
  1. var stringFromPerson = JSON.stringify(person);   
  2. /* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}"   */   
  3. var personFromString = JSON.parse(stringFromPerson);    
  4. /* personFromString is equal to person object  */  
11.避免使用eval()或Function构造函数

eval()和Function构造函数被称为脚本引擎,每次执行它们的时候都必须把源码转换成可执行的代码,这是非常昂过的操作。

var func1 = new Function(functionCode);  
  1. var func2 = eval(functionCode);  
12.避免使用with()方法

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

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

而不是这样用:

这样会更好:

这样会更快:
 为什么?数组长度arraynNumbers在每次loop迭代时都会被重新计算。 

14.不要向setTimeout()和setInterval()方法里传递字符串

如果在这两个方法里传递字符串,那么字符串会像eval那样重新计算,这样速度就会变慢,而不是这样使用:

setInterval('doSomethingPeriodically()', 1000);    
  1. setTimeOut('doSomethingAfterFiveSeconds()', 5000);  
相反,应该这样用:

setInterval(doSomethingPeriodically, 1000);    
  1. setTimeOut(doSomethingAfterFiveSeconds, 5000);  
15.使用switch/case语句代替较长的if/else语句

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

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

function getCategory(age) {    
  1.     var category = "";    
  2.     switch (true) {    
  3.         case isNaN(age):    
  4.             category = "not an age";    
  5.             break;    
  6.         case (age >= 50):    
  7.             category = "Old";    
  8.             break;    
  9.         case (age <= 20):    
  10.             category = "Baby";    
  11.             break;    
  12.         default:    
  13.             category = "Young";    
  14.             break;    
  15.     };    
  16.     return category;    
  17. }    
  18. getCategory(5);  // will return "Baby"  
17.创建一个对象,该对象的属性是一个给定的对象

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

function clone(object) {    
  1.     function OneShotConstructor(){};   
  2.     OneShotConstructor.prototype= object;    
  3.     return new OneShotConstructor();   
  4. }   
  5. clone(Array).prototype ;  // []  
18.一个HTML escaper函数

function escapeHTML(text) {    
  1.     var replacements= {"<""<"">"">","&""&""\"""""};                        
  2.     return text.replace(/[<>&"]/g, function(character) {    
  3.         return replacements[character];    
  4.     });   
  5. }  
19.在一个loop里避免使用try-catch-finally

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

不要这样使用:

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

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

如果一个XHR需要花费太长时间,你可以终止链接(例如网络问题),通过给XHR使用setTimeout()解决。

var xhr = new XMLHttpRequest ();   
  1. xhr.onreadystatechange = function () {    
  2.     if (this.readyState == 4) {    
  3.         clearTimeout(timeout);    
  4.         // do something with response data   
  5.     }    
  6. }    
  7. var timeout = setTimeout( function () {    
  8.     xhr.abort(); // call error callback    
  9. }, 60*1000 /* timeout after a minute */ );   
  10. xhr.open('GET', url, true);    
  11.   
  12. xhr.send();  
此外,通常你应该完全避免同步Ajax调用。

21.处理WebSocket超时

一般来说,当创建一个WebSocket链接时,服务器可能在闲置30秒后链接超时,在闲置一段时间后,防火墙也可能会链接超时。

为了解决这种超时问题,你可以定期地向服务器发送空信息,在代码里添加两个函数:一个函数用来保持链接一直是活的,另一个用来取消链接是活的,使用这种方法,你将控制超时问题。

添加一个timeID……

var timerID = 0;   
  1. function keepAlive() {   
  2.     var timeout = 15000;    
  3.     if (webSocket.readyState == webSocket.OPEN) {    
  4.         webSocket.send('');    
  5.     }    
  6.     timerId = setTimeout(keepAlive, timeout);    
  7. }    
  8. function cancelKeepAlive() {    
  9.     if (timerId) {    
  10.         cancelTimeout(timerId);    
  11.     }    
  12. }  
keepAlive()方法应该添加在WebSocket链接方法onOpen()的末端,cancelKeepAlive()方法放在onClose()方法下面。

22.记住,最原始的操作要比函数调用快

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

例如

var min = Math.min(a,b);   
  1. A.push(v);  
基本操作方式:

var min = a < b ? a b;   
  1. A[A.length] = v;  
23.编码时注意代码的美观、可读
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值