尽管我使用Javascript来作开发有不少年了,但它常有一些让我很惊讶的小特 性。对于我来讲,Javascript是须要持续不断的学习的。在这篇文章中,我将列出10个Javascript使用小技巧,主要面向 Javascript新手和中级开发者。但愿每一个读者都能至少从中学到一个有用的技巧。 node
看起来很简单,但据我所看到的,使用构造函数,像Array()或者Number()来进行变量转换是经常使用的作法。始终使用原始数据类型(有时也称为字面量)来转换变量,这种没有任何额外的影响的作法反而效率更高。
转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,并且建立正则表达式的时候要使用/pattern/flags的形式。 正则表达式
var myVar = "3.14159", str = ""+ myVar,// to string int = ~~myVar, // to integer float = 1*myVar, // to float bool = !!myVar, /* to boolean - any string with length and any number except 0 are true */ array = [myVar]; // to array
你是否是写个单独的函数来转换十六进制(或者八进制)呢?立刻停下吧!有更容易的现成的函数能够用: 浏览器
(int).toString(16); // converts int to hex, eg 12 => "C" (int).toString(8); // converts int to octal, eg. 12 => "14" parseInt(string,16) // converts hex to int, eg. "FF" => 255 parseInt(string,8) // converts octal to int, eg. "20" => 16
除了上一节介绍的以外,这里有更多的处理数字的技巧 app
0xFF; // Hex declaration, returns 255 020; // Octal declaration, returns 16 1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000 (1000).toExponential(); // Opposite with previous, returns 1e3 (3.1415).toFixed(3); // Rounding the number, returns "3.142"
你知道你的浏览器支持哪个版本的Javascript吗?若是不知道的话,去维基百科查一下Javascript版本表吧。出于某种原 因,Javascript 1.7版本的某些特性是没有获得普遍的支持。不过大部分浏览器都支持了1.8版和1.8.1版的特性。(注:全部的IE浏览器(IE8或者更老的版本)只 支持1.5版的Javascript)这里有一个脚本,既能经过检测特征来检测JavaScript版本,它还能检查特定的Javascript版本所支 持的特性。 函数
var JS_ver = []; (Number.prototype.toFixed)?JS_ver.push("1.5"):false; ([].indexOf && [].forEach)?JS_ver.push("1.6"):false; ((function(){ try { [a,b] = [0,1]; return true; }catch(ex) { return false; } })())?JS_ver.push("1.7"):false; ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false; ("".trimLeft)?JS_ver.push("1.8.1"):false; JS_ver.supports = function(){ if (arguments[0]) return (!!~this.join().indexOf(arguments[0] +",") +","); else return (this[this.length-1]); } alert("Latest Javascript version supported: "+ JS_ver.supports()); alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));
这个是我真的喜欢的东西。您能够为指定一个字符串做为window.name属性的值,直到您关闭该标签或窗口。虽然我没有提供任何脚本,但我强烈建议您如充分利用这个方法。举例来讲,在建设一个网站或应用程序的时候,在调试和测试模式之间切换是很是有用的。 oop
这个问题包含两个方面,既有检查属性时候存在,还要获取属性的类型。但咱们老是忽略了这些小事情: 布局
// BAD: This will cause an error in code when foo is undefined if (foo) { doSomething(); } // GOOD: This doesn't cause any errors. However, even when // foo is set to NULL or false, the condition validates as true if (typeof foo != "undefined") { doSomething(); } // BETTER: This doesn't cause any errors and in addition // values NULL or false won't validate as true if (window.foo) { doSomething(); }可是,有的状况下,咱们有更深的结构和须要更合适的检查的时候,能够这样:
// UGLY: we have to proof existence of every // object before we can be sure property actually exists if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) { doSomething(); }
当函数既有必选又有可选参数的时候,普通的作法是直接传递参数,而传递一个对象老是比传递一堆的参数更方便:
这只是一个把对象做为参数传递的一个很简单的例子,例如,咱们还能够声明一个对象,变量名做为Key,默认值做为Value。 学习
function doSomething() { // Leaves the function if nothing is passed if (!arguments[0]) { return false; } var oArgs = arguments[0] arg0 = oArgs.arg0 || "", arg1 = oArgs.arg1 || "", arg2 = oArgs.arg2 || 0, arg3 = oArgs.arg3 || [], arg4 = oArgs.arg4 || false; } doSomething({ arg1 : "foo", arg2 : 5, arg4 : false });
您可能须要动态地追加多个元素到文档中。然而,直接将它们插入到文档中会致使这个文档每次都须要从新布局一个,相反的,你应该使用文档碎片,建成后只追加一次: 测试
function createList() { var aLI = ["first item", "second item", "third item","fourth item", "fith item"]; // Creates the fragment var oFrag = document.createDocumentFragment(); while (aLI.length) { var oLI = document.createElement("li"); // Removes the first item from array and appends it // as a text node to LI element oLI.appendChild(document.createTextNode(aLI.shift())); oFrag.appendChild(oLI); } document.getElementById('myUL').appendChild(oFrag); }
有的时候你想替换字符串的某个部分为其它的值,最好的方法就是给String.replace()传递一个独立的函数。
下面是实如今线扑克游戏中大量输出的一个简单例子: 网站
var sFlop = "Flop: [Ah] [Ks] [7c]"; var aValues = {"A":"Ace","K":"King",7:"Seven"}; var aSuits = {"h":"Hearts","s":"Spades","d":"Diamonds","c":"Clubs"}; sFlop = sFlop.replace(/\[\w+\]/gi, function(match) { match = match.replace(match[2], aSuits[match[2]]); match = match.replace(match[1], aValues[match[1]] +" of "); return match; }); // string sFlop now contains: // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"
有的时候,循环中又嵌套了循环,你可能想在循环中退出,则能够用标签:
outerloop: for (var iI=0;iI<5;iI++) { if (somethingIsTrue()) { // Breaks the outer loop iteration break outerloop; } innerloop: for (var iA=0;iA<5;iA++) { if (somethingElseIsTrue()) { // Breaks the inner loop iteration break innerloop; } } }