javascript当中eval用法

eval
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。



例 4.1.1

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>

<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
/*马克-to-win:var scriptCode = "c = a * b";
   var a = 5;
   var b = 10;
   var c = 2;
   eval(scriptCode);
以上的话就相当于:
       eval("c = a * b");===c = a * b

eval是global的方法,
   */
var result = window.eval("1+2/4") ;//根据上面所说,result=1+2/4;
document.write(result)
var s="today=new Date();document.write(today.toLocaleString())"
eval(s)
//-->
</SCRIPT>
</BODY>
</HTML>

输出结果:
1.52018/1/2 下午12:09:18




例 4.1.2

<HTML>
<HEAD>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<TITLE>在eclipse中直接open with火狐即可</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
//例1
var s = "2+31-18";
/*When the eval() function is called, it expects a string to be
passed to it as its single argument value. The contents of that
string should be syntactically correct executable script source
text.*/

document.write(eval(s));
var s1 = "2+31a-18";
/* note that we must comment out the following statement,
otherwise, it reports error.*/
//document.write(eval(s1));

//例2
eval("d =new Date();document.write(d.toLocaleString())")
//eval()函数的参数为字符串,功能是将该字符串执行出来。体会“执行”的意思!
//-->
</SCRIPT>
</BODY>
</HTML>

输出结果:
152018/1/2 下午12:11:35




例 4.1.3

<HTML>
<HEAD>

<TITLE> New Document </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* 马克-to-win:the following two statements are both ok.*/
/* sometimes, we need to pass in a String, we have no way to pass in json.比如从java到javascript转换,We use the following way
to convert a string to a json.还记得json是object类型。 */

//var user ="{'name':'张','sex':'男','age':22}"
var user ="{name:'张',sex:'男',age:22}";
//若将该字符串转换为对象,则:
var obj = eval("("+user+")"); //多加一对()为语法要求
//var obj = eval(user);
document.write(obj.age);

/*马克-to-win :var a = ['hello' , 'java' , 'world'];
    for (index in a)
        document.writeln('索引' + index + '

的值是:' + a[index] + "<br>" );
             
the result is:
索引0的值是:hello
索引1的值是:java
索引2的值是:world

for (propName in navigator)
    {
        document.write('属性' + propName + '

的值是:' + navigator[propName]);
        document.write("<br />");
    }
     
the result is:
属性appCodeName的值是:Mozilla
属性appName的值是:Microsoft Internet Explorer

                */                              
                 for(var pro in obj)
                 {
document.write(pro+" is "+obj[pro]);
                 }


//-->
</SCRIPT>
</BODY>
</HTML>

输出结果:
22name is 张sex is 男age is 22




例 4.1.4

<HTML>
<HEAD>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<TITLE> New Document </TITLE>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
define =

"{name:'dfsdfael',email:'ggg@163.com'}";
 eval("data = "+define);
 document.write(data.name);
 document.write(data.email);

//-->
</SCRIPT>
</BODY>
</HTML>

输出结果:
dfsdfaelggg@163.com