你可能不知道的10个JavaScript小技巧

1.变量转换

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


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

(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


3.玩转数字

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"


4.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"));


6.判断属性是否存在

// 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();
}


7.给函数传递参数

function doSomething(arg0, arg1, arg2, arg3, arg4) {
...
}
doSomething('', 'foo', 5, [], false);


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
});


8.使用document.createDocumentFragment()

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);
}


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

var sFlop   = "Flop: [Ah] [Ks] [7c]";
var aValues = {"A":"Ace","K":"King",7:"Seven"};
"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]"


10.循环中标签的使用

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;
}
}
}

HTML和CSS你可能不知道的技巧

2016-09-20 12:30:03

你可能不知道的 10 条 SQL 技巧，涨知识了！

2017-12-07 09:49:52

你可能不知道的10个JavaScript小技巧

2010-09-24 19:03:00

10个你可能不知道的JavaScript小技巧

2013-09-03 15:57:25

你可能不知道的10个JavaScript小技巧 .

2013-12-11 01:19:08

你可能不知道的10个JavaScript小技巧

2010-09-01 09:54:00

[转]你可能不知道的10个JavaScript小技巧

2011-04-13 15:16:00

Spring的小窍门

2017-01-04 21:30:37

CSS3你可能不知道的冷知识

2016-12-02 22:05:28

你不知道的JavaScript（上、中、下）

2017年05月30日 25.46MB 下载