Javascript中eval函數的用法

JavaScript有許多小竅門來使編程更加容易。其中之一就是eval()函數,這個函數可以把一個字符串當作一個JavaScript表達式一樣去執行它。以下是它的說明

Eval 函數
功能:先解釋Javascript代碼,然後在執行它
用法:Eval(codeString)
codeString是包含有Javascript語句的字符串,在eval之後使用Javascript引擎編譯。 


舉個小例子:

var the_unevaled_answer = "2 + 3";
var the_evaled_answer = eval("2 + 3");
alert("the un-evaled answer is " + the_unevaled_answer + " and the evaled answer is " + the_evaled_answer);

如果你運行這段eval程序, 你將會看到在JavaScript裏字符串"2 + 3"實際上被執行了。所以當你把the_evaled_answer的值設成 eval("2 + 3")時, JavaScript將會明白並把2和3的和返回給the_evaled_answer。
這個看起來似乎有點傻,其實可以做出很有趣的事。比如使用eval你可以根據用戶的輸入直接創建函數。這可以使程序根據時間或用戶輸入的不同而使程序本身發生變化,通過舉一反三,你可以獲得驚人的效果。

在實際中,eval很少被用到,但也許你見過有人使用eval來獲取難以索引的對象。 文檔對象模型(DOM)的問題之一是:有時你要獲取你要求的對象簡直就是痛苦。例如,這裏有一個函數詢問用戶要變換哪個圖象:變換哪個圖象你可以用下面這個函數:

 

 

function swapOne()
{
 
var the_image = prompt("change parrot or cheese","");
 
var the_image_object;

 
if (the_image == "parrot")
 {
  the_image_object 
= window.document.parrot;
 } 
 
else 
 {
  the_image_object 
= window.document.cheese;
 }

 the_image_object.src 
= "ant.gif";
}

 

連同這些image標記:

 

<img src="/stuff3a/parrot.gif" name="parrot" />
<img src="/stuff3a/cheese.gif" name="cheese">

 

請注意象這樣的幾行語句:

 

the_image_object = window.document.parrot;


它把一個圖象對象敷給了一個變量。雖然看起來有點兒奇怪,它在語法上卻毫無問題。但當你有100個而不是兩個圖象時怎麼辦?你只好寫上一大堆的 if-then-else語句,要是能象這樣就好了:

function swapTwo()
{
 
var the_image = prompt("change parrot or cheese","");
 window.document.the_image.src 
= "ant.gif";
}


不幸的是, JavaScript將會尋找名字叫 the_image而不是你所希望的"cheese"或者"parrot"的圖象,於是你得到了錯誤信息:”沒聽說過一個名爲the_image的對象”。

還好,eval能夠幫你得到你想要的對象。

 

function simpleSwap()
{
 
var the_image = prompt("change parrot or cheese","");
 
var the_image_name = "window.document." + the_image;
 
var the_image_object = eval(the_image_name);
 the_image_object.src 
= "ant.gif";
}

 


如果用戶在提示框裏填入"parrot",在第二行裏創建了一個字符串即window.document.parrot. 然後包含了eval的第三行意思是: "給我對象window.document.parrot" - 也就是你要的那個圖象對象。一旦你獲取了這個圖象對象,你可以把它的src屬性設爲ant.gif. 其實這相當有用,人們也經常使用它。

發佈了10 篇原創文章 · 獲贊 5 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章