日期:2014-05-16 浏览次数:20501 次
view sourceprint? 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
view sourceprint? (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
view sourceprint? 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"
view sourceprint? 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"));
view sourceprint? // 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(); }
view sourceprint? // 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(); }
view sourceprint? function doSomething(arg0, arg1, arg2, arg3, arg4) { ... } doSomething('', 'foo', 5, [], false);
view sourceprint? function doSomething() { // Leaves the functi