JavaScript函数_eval()

eval():例1_先解释JavaScript代码,然后再执行它;例2_获取难以索引的对象。
例1:

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

结果:前者的值还是"2 + 3",而经过eval后的值则是5。

例2:有一个函数询问用户要变换哪个图象,可以用下面这个函数:  

  1. function swapOne()
  2. {
  3.     var the_image = prompt("change parrot or cheese","");
  4.     var the_image_object;
  5.     if (the_image == "parrot")
  6.     {
  7.         the_image_object = window.document.parrot;
  8.     }
  9.     else
  10.     { 
  11.         the_image_object = window.document.cheese;
  12.     }
  13.     the_image_object.src = "ant.gif";
  14. }

html代码: 

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

请注意这样的语句:

the_image_object = window.document.parrot;

它把一个鹦鹉图象对象赋给了一个变量。但当你有100个而不是两个图象时怎么办?你只好写上一大堆的 if-then-else语句,要是能象这样就好了:

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

不幸的是, JavaScript将会寻找名字叫the_image而不是你所希望的"cheese"或者"parrot"的图象,于是你得到了错误信息:“没找到一个名为the_image的对象”。
还好,eval能够帮你得到你想要的对象。   

  1. function simpleSwap()
  2. {
  3.     var the_image = prompt("change parrot or cheese","");
  4.     var the_image_name = "window.document." + the_image;
  5.     var the_image_object = eval(the_image_name);
  6.     the_image_object.src = "ant.gif";
  7. }

如果用户在提示框里填入"parrot",在第二行里创建了字符串window.document.parrot. 然后包含了eval的第三行意思是:“给我对象window.document.parrot”,也就是你要的那个图象对象。一旦你获取了这个图象对象,你就可以把它的src属性设为ant.gif,甚至做更多你想做的事情。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值