Javascript中eval函數的用法

來源:互聯網
上載者:User

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. 有點害怕?用不著。其實這相當有用,人們也經常使用它。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.