45个超实用的JavaScript技巧及最佳实践(一)
21. 使用逻辑AND/OR来处理条件语句
- 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
 - }
 
22. 使用map()函数方法来循环数组里的项目
- var squares =[1,2,3,4].map(function(val){
 - return val * val;
 - });
 - // squares will be equal to [1, 4, 9, 16]
 
23. 按小数点后N位来四舍五入
- var num =2.443242342;
 - num = num.toFixed(4);// num will be equal to 2.4432
 
24. 浮点问题
- 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 。你应该知道所有的javascript数字在64位2进制内部都是使用浮点表示
这个来自于IEEE 754标准。更多信息介绍,请参考:相关博客
你可以使用上面介绍的toFixed()和toPrecision()来解决这个问题
25. 使用for-in循环来检查对象的指定属性
下面的代码片段非常实用,可以避免从对象的prototype来循环遍历对象的属性:
- for(var name inobject){
 - if(object.hasOwnProperty(name)){
 - // do something with name
 - }
 - }
 
26. 逗号操作符
- var a =0;
 - var b =( a++,99);
 - console.log(a);// a will be equal to 1
 - console.log(b);// b is equal to 99
 
27. 缓存需要计算或者DOM查询的变量
使用jQuery的选择器,我们一定要记住缓存DOM元素,这样会提高执行效率:
- var navright = document.querySelector('#right');
 - var navleft = document.querySelector('#left');
 - var navup = document.querySelector('#up');
 - var navdown = document.querySelector('#down');
 
28. 在传入isFinite()之前验证参数
- isFinite(0/0);// false
 - isFinite("foo");// false
 - isFinite("10");// true
 - isFinite(10);// true
 - isFinite(undifined);// false
 - isFinite();// false
 - isFinite(null);// true !!!
 
29. 避免数组中index为负值
- var numbersArray =[1,2,3,4,5];
 - varfrom= numbersArray.indexOf("foo");// from is equal to -1
 - numbersArray.splice(from,2);// will return [5]
 
这里需要注意indexof的参数 不能为负值,但是splice可以
30. 序列化和反序列化(用来处理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 */
 
31. 避免使用eval或者Function构建器
使用eval或者function构建器是一件非常消耗资源的操作,因为每次调用script引擎都必须将源代码转换为可执行的代码
- var func1 =newFunction(functionCode);//避免使用!!
 - var func2 =eval(functionCode);//避免使用!!
 
32. 避免使用with()
使用with()可以用来插入一个变量到全局。然而,如果另外一个变量拥有同样的名字,将会导致非常混乱并且会覆盖数值
33. 避免在数组中使用for-in循环
不推荐使用:
- 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];
 - }
 
作为额外的好处,i和len的实例化都执行一次,因为都是循环中的第一个语句,但是比下面执行速度更快:
- for(var i =0; i < arrayNumbers.length; i++)
 
为什么? arrayNumbers的长度在每次循环都计算一次
34. 传递函数,而非字符串到setTimeout()和setInterval()中
如果你传递一个字符串到setTimeout和setInterval中,处理方式和eval将会类似,速度会很慢,不要使用如下:
- setInterval('doSomethingPeriodically()',1000);
 - setTimeOut('doSomethingAfterFiveSeconds()',5000);
 
推荐使用如下
- setInterval(doSomethingPeriodically,1000);
 - setTimeOut(doSomethingAfterFiveSeconds,5000);
 
35. 使用switch/case语句而非一系列的if/else
如果多余两个条件,使用switch/case将会更快,而且语法更优雅(代码组织的更好)。对于多余10个条件的避免使用。
36. 使用switch/case语句处理数值区域
使用如下小技巧处理数值区域:
- 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"
 
37. 创建一个prototype是指定对象的对象
使用如下代码可以生成一个prototype是指定对象的对象:
- function clone(object){
 - functionOneShotConstructor(){};
 - OneShotConstructor.prototype=object;
 - returnnewOneShotConstructor();
 - }
 - clone(Array).prototype ;// []
 
39. 一个HTMLescaper方法
- function escapeHTML(text){
 - var replacements={"<":"<",">":">","&":"&","\"":"""};
 - return text.replace(/[<>&"]/g,function(character){
 - return replacements[character];
 - });
 - }
 
编译:当然,前台处理并不安全,后台处理更彻底
40. 在循环中避免使用try-catch-finally
不要使用如下代码:
- varobject=['foo','bar'], i;
 - for(i =0, len =object.length; i <len; i++){
 - try{
 - // do something that throws an exception
 - }
 - catch(e){
 - // handle exception
 - }
 - }
 
使用这段代码:
- varobject=['foo','bar'], i;
 - try{
 - for(i =0, len =object.length; i <len; i++){
 - // do something that throws an exception
 - }
 - }
 - catch(e){
 - // handle exception
 - }
 
40. 设置XMLHttpRequests的timeout
如果一个XHR花费了太多时间,你可以在XHR调用中使用setTimeout来退出连接:
- var xhr =newXMLHttpRequest();
 - 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调用
41. 处理WebSocket timeout
一般来说,当一个websocket连接建立后,服务器可以在30秒无响应的情况下time out你的连接。防火墙也可以做到。
为了处理timeout问题,你可以定时发送一个空的消息到服务器。为了实现,你可以添加两个方法到你的代码中:
一个保证连接的存在,另外一个取消连接。使用这个技巧,你可以处理timeout问题:
- 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添加到webSocket的onClose函数最后。
42. 记住,操作符比函数调用更快
不推荐使用:
- var min =Math.min(a,b);
 - A.push(v);
 
推荐使用:
- var min = a < b ? a:b;
 - A[A.length]= v;
 
43. 不要忘记使用代码美化工具。在代码产品化前使用JSLint和代码压缩工具(例如,JSMin)来处理
http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript










