事半功倍!JavaScript十个实用小技巧
6.判断属性是否存在
这个问题包含两个方面,既有检查属性时候存在,还要获取属性的类型。但我们总是忽略了这些小事情:
01 // BAD: This will cause an error in code when foo is undefined
02 if (foo) {
03 doSomething();
04 }
05 // GOOD: This doesn't cause any errors. However, even when
06 // foo is set to NULL or false, the condition validates as true
07 if (typeof foo != "undefined") {
08 doSomething();
09 }
10 // BETTER: This doesn't cause any errors and in addition
11 // values NULL or false won't validate as true
12 if (window.foo) {
13 doSomething();
14 }
02 if (foo) {
03 doSomething();
04 }
05 // GOOD: This doesn't cause any errors. However, even when
06 // foo is set to NULL or false, the condition validates as true
07 if (typeof foo != "undefined") {
08 doSomething();
09 }
10 // BETTER: This doesn't cause any errors and in addition
11 // values NULL or false won't validate as true
12 if (window.foo) {
13 doSomething();
14 }
但是,有的情况下,我们有更深的结构和需要更合适的检查的时候,可以这样:
1 // UGLY: we have to proof existence of every
2 // object before we can be sure property actually exists
3 if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
4 doSomething();
5 }
2 // object before we can be sure property actually exists
3 if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
4 doSomething();
5 }
7.给函数传递参数
当函数既有必选又有可选参数的时候,我们可能是这样做的:
1 function doSomething(arg0, arg1, arg2, arg3, arg4) {
2 ...
3 }
4 doSomething('', 'foo', 5, [], false);
2 ...
3 }
4 doSomething('', 'foo', 5, [], false);
而传递一个对象总是比传递一堆的参数更方便:
01 function doSomething() {
02 // Leaves the function if nothing is passed
03 if (!arguments[0]) {
04 return false;
05 }
06 var oArgs = arguments[0]
07 arg0 = oArgs.arg0 || "",
08 arg1 = oArgs.arg1 || "",
09 arg2 = oArgs.arg2 || 0,
10 arg3 = oArgs.arg3 || [],
11 arg4 = oArgs.arg4 || false;
12 }
13 doSomething({
14 arg1 : "foo",
15 arg2 : 5,
16 arg4 : false
17 });
02 // Leaves the function if nothing is passed
03 if (!arguments[0]) {
04 return false;
05 }
06 var oArgs = arguments[0]
07 arg0 = oArgs.arg0 || "",
08 arg1 = oArgs.arg1 || "",
09 arg2 = oArgs.arg2 || 0,
10 arg3 = oArgs.arg3 || [],
11 arg4 = oArgs.arg4 || false;
12 }
13 doSomething({
14 arg1 : "foo",
15 arg2 : 5,
16 arg4 : false
17 });
这只是一个把对象作为参数传递的一个很简单的例子,例如,我们还可以声明一个对象,变量名作为Key,默认值作为Value。
8.使用document.createDocumentFragment()
您可能需要动态地追加多个元素到文档中。然而,直接将它们插入到文档中会导致这个文档每次都需要重新布局一个,相反的,你应该使用文档碎片,建成后只追加一次:
1 function doSomething(arg0, arg1, arg2, arg3, arg4) {
2 ...
3 }
4 doSomething('', 'foo', 5, [], false);
2 ...
3 }
4 doSomething('', 'foo', 5, [], false);
而传递一个对象总是比传递一堆的参数方便:
01 function createList() {
02 var aLI = ["first item", "second item", "third item",
03 "fourth item", "fith item"];
04 // Creates the fragment
05 var oFrag = document.createDocumentFragment();
06 while (aLI.length) {
07 var oLI = document.createElement("li");
08 // Removes the first item from array and appends it
09 // as a text node to LI element
10 oLI.appendChild(document.createTextNode(aLI.shift()));
11 oFrag.appendChild(oLI);
12 }
13 document.getElementById('myUL').appendChild(oFrag);
14 }
02 var aLI = ["first item", "second item", "third item",
03 "fourth item", "fith item"];
04 // Creates the fragment
05 var oFrag = document.createDocumentFragment();
06 while (aLI.length) {
07 var oLI = document.createElement("li");
08 // Removes the first item from array and appends it
09 // as a text node to LI element
10 oLI.appendChild(document.createTextNode(aLI.shift()));
11 oFrag.appendChild(oLI);
12 }
13 document.getElementById('myUL').appendChild(oFrag);
14 }
9.为replace()方法传递一个函数
有的时候你想替换字符串的某个部分为其它的值,最好的方法就是给String.replace()传递一个独立的函数。
下面是实现在线扑克游戏中大量输出的一个简单例子:
01 var sFlop = "Flop: [Ah] [Ks] [7c]";
02 var aValues = {"A":"Ace","K":"King",7:"Seven"};
03 var aSuits = {"h":"Hearts","s":"Spades",
04 "d":"Diamonds","c":"Clubs"};
05 sFlop = sFlop.replace(/\[\w+\]/gi, function(match) {
06 match = match.replace(match[2], aSuits[match[2]]);
07 match = match.replace(match[1], aValues[match[1]] +" of ");
08 return match;
09 });
10 // string sFlop now contains:
11 // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"
02 var aValues = {"A":"Ace","K":"King",7:"Seven"};
03 var aSuits = {"h":"Hearts","s":"Spades",
04 "d":"Diamonds","c":"Clubs"};
05 sFlop = sFlop.replace(/\[\w+\]/gi, function(match) {
06 match = match.replace(match[2], aSuits[match[2]]);
07 match = match.replace(match[1], aValues[match[1]] +" of ");
08 return match;
09 });
10 // string sFlop now contains:
11 // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"
10.循环中标签的使用
有的时候,循环中又嵌套了循环,你可能想在循环中退出,则可以用标签:
01 outerloop:
02 for (var iI=0;iI<5;iI++) {
03 if (somethingIsTrue()) {
04 // Breaks the outer loop iteration
05 break outerloop;
06 }
07 innerloop:
08 for (var iA=0;iA<5;iA++) {
09 if (somethingElseIsTrue()) {
10 // Breaks the inner loop iteration
11 break innerloop;
12 }
13 }
14 }
02 for (var iI=0;iI<5;iI++) {
03 if (somethingIsTrue()) {
04 // Breaks the outer loop iteration
05 break outerloop;
06 }
07 innerloop:
08 for (var iA=0;iA<5;iA++) {
09 if (somethingElseIsTrue()) {
10 // Breaks the inner loop iteration
11 break innerloop;
12 }
13 }
14 }
0
相关文章