尽管我使用Javascript来做开发有很多年了,但它常有一些让我很惊讶的小特性。对于我来说,Javascript是需要持续不断的学习的。在这篇文章中,我将列出10个Javascript使用小技巧,主要面向Javascript新手和中级开发者。希望每个读者都能至少从中学到一个有用的技巧。
1.变量转换
view sourceprint? 2 str = ""+ myVar,// to string 3 int = ~~myVar, // to integer 4 float = 1*myVar, // to float 5 bool = !!myVar, /* to boolean - any string with length 6 and any number except 0 are true */
7 array = [myVar]; // to array
view sourceprint? 2 (int).toString(8); // converts int to octal, eg. 12 => "14" 3 parseInt(string,16) // converts hex to int, eg. "FF" => 255
4 parseInt(string,8) // converts octal to int, eg. "20" => 16
view sourceprint? 2 020; // Octal declaration, returns 16 3 1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000 4 (1000).toExponential(); // Opposite with previous, returns 1e3
5 (3.1415).toFixed(3); // Rounding the number, returns "3.142"
view sourceprint? 02 (Number.prototype.toFixed)?JS_ver.push("1.5"):false; 03 ([].indexOf && [].forEach)?JS_ver.push("1.6"):false; 04 ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false; 05 ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false; 06 ("".trimLeft)?JS_ver.push("1.8.1"):false; 07 JS_ver.supports = function() 08 { 09 if (arguments[0]) 10 return (!!~this.join().indexOf(arguments[0] +",") +","); 11 else 12 return (this[this.length-1]); 13 } 14 alert("Latest Javascript version supported: "+ JS_ver.supports());
15 alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));
6.判断属性是否存在
view sourceprint? 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 }
view sourceprint? 2 // object before we can be sure property actually exists 3 if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) { 4 doSomething();
5 }
view sourceprint? 2 ... 3 }
4 doSomething('', 'foo', 5, [], false);
view sourceprint? 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 });
8.使用document.createDocumentFragment()
view sourceprint? 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 }
view sourceprint? 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]"
view sourceprint? 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 } (责任编辑:机器AI) |