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_p_w_picpath = prompt("change parrot or cheese",""); var the_p_w_picpath_object; if (the_p_w_picpath == "parrot") { the_p_w_picpath_object = window.document.parrot; } else { the_p_w_picpath_object = window.document.cheese; } the_p_w_picpath_object.src = "ant.gif"; } 连同这些p_w_picpath标记: [img src="stuff3a/parrot.gif" name="parrot"] [img src="stuff3a/cheese.gif" name="cheese"] 请注意象这样的几行语句: the_p_w_picpath_object = window.document.parrot; 它把一个图象对象敷给了一个变量。虽然看起来有点儿奇怪,它在语法上却毫无问题。 但当你有100个而不是两个图象时怎么办?你只好写上一大堆的 if-then-else语句,要是能象这样就行了: function swapTwo() { var the_p_w_picpath = prompt("change parrot or cheese",""); window.document.the_p_w_picpath.src = "ant.gif"; } 不幸的是, JavaScript将会寻找名字叫 the_p_w_picpath而不是你所但愿的"cheese"或者"parrot"的图象, 因而你获得了错误信息:”没据说过一个名为the_p_w_picpath的对象”。 还好,eval可以帮你获得你想要的对象。 function simpleSwap() { var the_p_w_picpath = prompt("change parrot or cheese",""); var the_p_w_picpath_name = "window.document." + the_p_w_picpath; var the_p_w_picpath_object = eval(the_p_w_picpath_name); the_p_w_picpath_object.src = "ant.gif"; }下面是JScript中的原文:
eval 方法
检查 JScript 代码并执行.
eval( codeString)
必选项 codestring 参数是包含有效 JScript 代码的字符串值。这个字符串将由 JScript 分析器进行分析和执行。
说明
eval 函数容许 JScript 源代码的动态执行。例如,下面的代码建立了一个包含 Date 对象的新变量 mydate :
eval("var mydate = new Date();");
传递给 eval 方法的代码执行时的上下文和调用 eval 方法的同样.
若是你仍是跟我同样不是很明白的话,请继续看下面的例子:
JS从页面上得到一个标签的ID赋予theid,而后定义一个变量获得这个对象,代码以下:
if(theid == "mydiv"){
var thediv = window.document.theid;
}
若是页面上有上百个这样的div,难道要写上百个if吗,答案确定是否认的,也许你会这么写:
var thediv = "window.document" + theid;
但是这样获得的thediv是一个字符串,不是一个对象,但能够用Eval()函数来解决这个问题,代码以下:
var myobject = "window.document" + theid;
var thediv = eval(myobject);
这样获得的thediv就是一个对象了。。。ide原文出自:http://blog.csdn.net/hellollx/article/details/4519223函数