日期:2014-05-16  浏览次数:20414 次

javascript 中的eval方法 小窍门
eval()函数
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";
}

<script type="text/javascript"></script>