1.变量转换

看起来很简单,但据我所看到的,使用构造函数,像Array()或者Number()来进行变量转换是常用的做法。始终使用原始数据类型(有时也称为字面量)来转换变量,这种没有任何额外的影响的做法反而效率更高。


1. var myVar = "3.14159",  
2. ""+ myVar,// to string 
3. int = ~~myVar, // to integer 
4. float = 1*myVar, // to float 
5. /* to boolean - any string with length 
6.  and any number except 0 are true */
7. // to array

转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,而且创建正则表达式的时候要使用/pattern/flags的形式。

2.十进制转换为十六进制或者八进制,或者反过来

你是不是写个单独的函数来转换十六进制(或者八进制)呢?马上停下吧!有更容易的现成的函数可以用:


1. int).toString(16); // converts int to hex, eg 12 => "C" 
2. int).toString(8); // converts int to octal, eg. 12 => "14" 
3. // converts hex to int, eg. "FF" => 255 
4. // converts octal to int, eg. "20" => 16

3.玩转数字

除了上一节介绍的之外,这里有更多的处理数字的技巧:

1. // Hex declaration, returns 255 
2. // Octal declaration, returns 16 
3. // Exponential, same as 1 * Math.pow(10,3), returns 1000 
4. // Opposite with previous, returns 1e3 
5. // Rounding the number, returns "3.142"

4.Javascript版本检测

你知道你的浏览器支持哪一个版本的Javascript吗?如果不知道的话,去维基百科查一下Javascript版本表吧。出于某种原因,Javascript 1.7版本的某些特性是没有得到广泛的支持。不过大部分浏览器都支持了1.8版和1.8.1版的特性。(注:所有的IE浏览器(IE8或者更老的版本)只支持1.5版的Javascript)这里有一个脚本,既能通过检测特征来检测JavaScript版本,它还能检查特定的Javascript版本所支持的特性。




1. var
2. 
3. "1.5"):false;  
4. "1.6"):false;  
5. function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;  
6. "1.8"):false;  
7. "".trimLeft)?JS_ver.push("1.8.1"):false;  
8. 
9. function()  
10.  {  
11. if
12. return (!!~this.join().indexOf(arguments[0] +",") +",");  
13. else
14. return (this[this.length-1]);  
15.   }  
16. 
17. "Latest Javascript version supported: "+ JS_ver.supports());  
18. "Support for version 1.7 : "+ JS_ver.supports("1.7"));

5.使用window.name进行简单会话处理

这个是我真的喜欢的东西。您可以为指定一个字符串作为window.name属性的值,直到您关闭该标签或窗口。虽然我没有提供任何脚本,但我强烈建议您如充分利用这个方法。举例来说,在建设一个网站或应用程序的时候,在调试和测试模式之间切换是非常有用的。

6.判断属性是否存在

这个问题包含两个方面,既有检查属性时候存在,还要获取属性的类型。但我们总是忽略了这些小事情:

1. // BAD: This will cause an error in code when foo is undefined 
2. if
3.   doSomething();  
4.   }  
5. 
6. // GOOD: This doesn't cause any errors. However, even when 
7. // foo is set to NULL or false, the condition validates as true 
8. if (typeof foo != "undefined") {  
9.   doSomething();  
10.   }  
11. 
12. // BETTER: This doesn't cause any errors and in addition 
13. // values NULL or false won't validate as true 
14. if
15.   doSomething();  
16.  }

但是,有的情况下,我们有更深的结构和需要更合适的检查的时候,可以这样:


1. // UGLY: we have to proof existence of every 
2. // object before we can be sure property actually exists 
3. 
4. if
5.   doSomething();  
6.   }

7.给函数传递参数

当函数既有必选又有可选参数的时候,我们可能是这样做的:


1. function
2.   ...  
3.   }  
4. 
5. '', 'foo', 5, [], false);

而传递一个对象总是比传递一堆的参数更方便:


1. function
2. 
3. // Leaves the function if nothing is passed 
4. if
5. return false;  
6.   }  
7. 
8. var
9. "",  
10. "",  
11.   arg2 = oArgs.arg2 || 0,  
12.   arg3 = oArgs.arg3 || [],  
13. false;  
14.  }  
15. 
16.  doSomething({  
17. "foo",  
18.   arg2 : 5,  
19. false
20.   });

这只是一个把对象作为参数传递的一个很简单的例子,例如,我们还可以声明一个对象,变量名作为Key,默认值作为Value。

8.使用document.createDocumentFragment()

您可能需要动态地追加多个元素到文档中。然而,直接将它们插入到文档中会导致这个文档每次都需要重新布局一个,相反的,你应该使用文档碎片,建成后只追加一次:


1. function
2.   ...  
3.   }  
4. 
5. '', 'foo', 5, [], false);

而传递一个对象总是比传递一堆的参数方便:

1. function
2. var aLI = ["first item", "second item", "third item","fourth item", "fith item"];  
3. 
4. // Creates the fragment 
5. var
6. 
7. while
8. var oLI = document.createElement("li");  
9. 
10. // Removes the first item from array and appends it 
11. // as a text node to LI element 
12.   oLI.appendChild(document.createTextNode(aLI.shift()));  
13.   oFrag.appendChild(oLI);  
14.   }  
15. 
16. 'myUL').appendChild(oFrag);  
17. 
18.   }

9.为replace()方法传递一个函数

有的时候你想替换字符串的某个部分为其它的值,最好的方法就是给String.replace()传递一个独立的函数。

下面是实现在线扑克游戏中大量输出的一个简单例子:


1. var sFlop = "Flop: [Ah] [Ks] [7c]";  
2. var aValues = {"A":"Ace","K":"King",7:"Seven"};  
3. var aSuits = {"h":"Hearts","s":"Spades","d":"Diamonds","c":"Clubs"};  
4. 
5. function(match) {  
6.   match = match.replace(match[2], aSuits[match[2]]);  
7. " of ");  
8. 
9. return
10.   });  
11. 
12. // string sFlop now contains: 
13. // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

10.循环中标签的使用

有的时候,循环中又嵌套了循环,你可能想在循环中退出,则可以用标签:

1.  outerloop:  
2. 
3. for (var
4. if
5. // Breaks the outer loop iteration 
6. break
7.   }  
8. 
9.  innerloop:  
10. 
11. for (var
12. if
13. // Breaks the inner loop iteration 
14. break
15.   }  
16.   }  
17.   }

 

个人签名

-------------------------------------