Eval 函數
功能:先解釋Javascript代碼,然後在執行它
用法:Eval(codeString)
codeString是包含有Javascript語句的字串,在eval之後使用Javascript引擎編譯。
舉例1:通過Eval執行指令碼
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你可以根據使用者的輸入直接建立函數。這可以使程式根據時間或使用者輸入的不同而使程式本身發生變化,通過舉一反三,你可以獲得驚人的效果。
舉例2:通過Eval獲的對象
實現: 一個函數詢問使用者要變換哪個圖象
非Eval實現指令碼:
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">
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";
}