eval()方法有了点感觉

本文通过两个实例探讨了JavaScript中eval()函数的使用方法及其特点。eval()能够将字符串作为代码执行,表现出类似自我复制的能力,并赋予字符串指向性的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Evaluates a string and executes it as if it was script code

 

"动态解析!"

 

找了下面两个例子,对eval()方法有了些感觉.感觉这个东东像是那种病毒,它自己可以自我复制,又像是又一套执行环境,它里面可以执行String类型的句子,

<html>
<body>

<script type="text/javascript">

    try{
        alert("Result: "+eval(prompt("Enter an expression: "," ")) );
    }catch(exception){
        alert(exception);
    }

</script>

</body>
</html>

在这个网页面里实验"http://www.w3schools.com/DHTML/tryit.asp?filename=trydhtml_randombanner"
<html>
<body>

        <script type="text/javascript">
            image0="/banners/w3schools.gif";
            href0="/default.asp";
            alt0="W3Schools.com";

            image1="/banners/rd_htmlref.jpg";
            href1="http://www.w3schools.com/html/html_reference.asp";
            alt1="HTML Reference";

            image2="/banners/rd_xhtml.jpg";
            href2="http://www.w3schools.com/xhtml/default.asp";
            alt2="ASP Free";

            len=3;

            now=new Date();
            now=now.getSeconds();
            rnd=now%len;

            image=eval("image"+rnd);
            href=eval("href"+rnd);
            alt=eval("alt"+rnd);

            document.write("I am Here:" + image + "<hr> " + rnd + "<hr> " );

            document.write("<a href='" + href + "'>");
            document.write("<img src='" + image + "' alt='" + alt + "'></a>");    
        </script>

    <h3>Refresh this page to see the banner change</h3>

</body>
</html>


image=eval("image"+rnd);
href=eval("href"+rnd);
alt=eval("alt"+rnd);
改为:
image="image"+rnd;
href="href"+rnd;
alt="alt"+rnd;

后,出事了,

现象如下:
这是改后的显示:"I am Here: image2",改前的显示为"I am Here: /banners/w3schools.gif".

自己拼的字符串仅仅是一个干巴巴的字符串,而用eval()后的字符串就有了指针的灵性!!!

 

 

现在感觉这个eval()就像Java里的源代码调用自己的.class一样,eval()自己可以自我编译.

可这个与JSON又有什么关系呢?还是感觉不出什么必然的联系.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值