Posted on 2010-08-12 17:39
啥都寫點 閱讀(67)
評論(0) 編輯 收藏
盡管我使用Javascript來做開發有很多年了,但它常有一些讓我很驚訝的小特
性。對于我來說,Javascript是需要持續不斷的學習的。在這篇文章中,我將列出10個Javascript使用小技巧,主要面向
Javascript新手和中級開發者。希望每個讀者都能至少從中學到一個有用的技巧。
1.變量轉換
看起來很簡單,但據我所看到的,使用構造函數,像Array()或者Number()
來進行變量轉換是常用的做法。始終使用原始數據類型(有時也稱為字面量)來轉換變量,這種沒有任何額外的影響的做法反而效率更高。
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 |
轉換日期(new Date(myVar))和正則表達式(new
RegExp(myVar))必須使用構造函數,而且創建正則表達式的時候要使用/pattern/flags的形式。
2.十進制轉換為十六進制或者八進制,或者反過來
你是不是寫個單獨的函數來轉換十六進制(或者八進制)呢?馬上停下吧!有更容易的現成的函數可以用:
1 |
(int).toString(16); // converts int to hex, eg 12 => "C" |
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 |
3.玩轉數字
除了上一節介紹的之外,這里有更多的處理數字的技巧
1 |
0xFF; // Hex
declaration, returns 255 |
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" |
4.Javascript版本檢測
你知道你的瀏覽器支持哪一個版本的Javascript嗎?如果不知道的話,去維基百科查一下Javascript版本表吧。出于某種原
因,Javascript
1.7版本的某些特性是沒有得到廣泛的支持。不過大部分瀏覽器都支持了1.8版和1.8.1版的特性。(注:所有的IE瀏覽器(IE8或者更老的版本)只
支持1.5版的Javascript)這里有一個腳本,既能通過檢測特征來檢測JavaScript版本,它還能檢查特定的Javascript版本所支
持的特性。
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 () |
10 |
return (!!~ this .join().indexOf(arguments[0]
+ "," ) + "," ); |
12 |
return ( this [ this .length-1]); |
14 |
alert( "Latest Javascript version supported: " + JS_ver.supports()); |
15 |
alert( "Support for version 1.7 : " + JS_ver.supports( "1.7" )); |
5.使用window.name進行簡單會話處理
這個是我真的喜歡的東西。您可以為指定一個字符串作為window.name屬性的值,直到您關閉該標簽或窗口。雖然我沒有提供任何腳本,但我強烈
建議您如充分利用這個方法。舉例來說,在建設一個網站或應用程序的時候,在調試和測試模式之間切換是非常有用的。
6.判斷屬性是否存在
這個問題包含兩個方面,既有檢查屬性時候存在,還要獲取屬性的類型。但我們總是忽略了這些小事情:
01 |
// BAD: This will cause an error in code when
foo is undefined |
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" ) { |
10 |
// BETTER: This doesn't
cause any errors and in addition |
11 |
// values NULL or false
won't validate as true |
但是,有的情況下,我們有更深的結構和需要更合適的檢查的時候,可以這樣:
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) { |
7.給函數傳遞參數
當函數既有必選又有可選參數的時候,我們可能是這樣做的:
1 |
function doSomething(arg0,
arg1, arg2, arg3, arg4) { |
4 |
doSomething( '' , 'foo' , 5, [],
false ); |
而傳遞一個對象總是比傳遞一堆的參數更方便:
01 |
function doSomething()
{ |
02 |
// Leaves
the function if nothing is passed |
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 ; |
這只是一個把對象作為參數傳遞的一個很簡單的例子,例如,我們還可以聲明一個對象,變量名作為Key,默認值作為Value。
8.使用document.createDocumentFragment()
您可能需要動態地追加多個元素到文檔中。然而,直接將它們插入到文檔中會導致這個文檔每次都需要重新布局一個,相反的,你應該使用文檔碎片,建成后
只追加一次:
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(); |
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); |
13 |
document.getElementById( 'myUL' ).appendChild(oFrag); |
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 " ); |
10 |
// string sFlop now
contains: |
11 |
// "Flop: [Ace of Hearts] [King of Spades]
[Seven of Clubs]" |
10.循環中標簽的使用
有的時候,循環中又嵌套了循環,你可能想在循環中退出,則可以用標簽:
02 |
for ( var iI=0;iI<5;iI++) { |
03 |
if (somethingIsTrue())
{ |
04 |
// Breaks
the outer loop iteration |
08 |
for ( var iA=0;iA<5;iA++)
{ |
09 |
if
(somethingElseIsTrue()) { |
10 |
// Breaks the inner loop iteration |
英文來源:10 Small Things You May Not Know
About Javascript
--
學海無涯