javascriptÖеÄevalº¯ÊýµÄÓ÷¨(תÌù)
±¾ÎĵÄÁ½¸öÄ¿µÄ£º
£¨1£©½éÉÜjavascriptÖеÄevalº¯ÊýµÄÓ÷¨
£¨2£©ÈçºÎÔÚº¯ÊýÄÚÖ´ÐÐÈ«¾Ö´úÂë
►ÏÈÀ´ËµevalµÄÓ÷¨£¬ÄÚÈݱȽϼòµ¥£¬ÊìϤµÄ¿ÉÒÔÌø¹ý¡£
evalº¯Êý½ÓÊÕÒ»¸ö²ÎÊýs£¬Èç¹ûs²»ÊÇ×Ö·û´®£¬ÔòÖ±½Ó·µ»Øs¡£·ñÔòÖ´ÐÐsÓï¾ä¡£Èç¹ûsÓï¾äÖ´Ðнá¹ûÊÇÒ»¸öÖµ£¬Ôò·µ»Ø´ËÖµ£¬·ñÔò·µ»Øundefined¡£
ÐèÒªÌرð×¢ÒâµÄÊǶÔÏóÉùÃ÷Óï·¨“{}”²¢²»ÄÜ·µ»ØÒ»¸öÖµ£¬ÐèÒªÓÃÀ¨ºÅÀ¨ÆðÀ´²Å»á·µ»ØÖµ£¬¼òµ¥Ê¾ÀýÈçÏ£º
var code1='"a" + 2'; //±í´ïʽ
var code2='{a:2}'; //Óï¾ä
alert(eval(code1)); //->'a2'
alert(eval(code2)); //->undefined
alert(eval('(' + code2 + ')')); //->[object Object]
¸´ÖÆ´úÂë
¿ÉÒÔ¿´µ½£¬¶ÔÓÚ¶ÔÏóÉùÃ÷Óï¾äÀ´Ëµ£¬½ö½öÊÇÖ´ÐУ¬²¢²»ÄÜ·µ»ØÖµ¡£ÎªÁË·µ»Ø³£Óõē{}”ÕâÑùµÄ¶ÔÏóÉùÃ÷Óï¾ä£¬±ØÐëÓÃÀ¨ºÅÀ¨×¡£¬ÒÔ½«Æäת»»Îª±í´ïʽ£¬²ÅÄÜ·µ»ØÆäÖµ¡£ÕâÒ²ÊÇʹÓÃJSONÀ´½øÐÐAjax¿ª·¢µÄ»ù±¾ÔÀíÖ®Ò»¡£ÔÚÀý×ÓÖпÉÒÔÇå³þµÄ¿´µ½£¬µÚ¶þ¸öalertÓï¾äÊä³öµÄÊÇundefined£¬¶øµÚÈý¸ö¼ÓÁËÀ¨ºÅºóÊä³öµÄÊÇÓï¾ä±íʾµÄ¶ÔÏó¡£
►ÏÖÔÚÀ´Ëµ±¾ÎĵÄÖص㣬ÈçºÎÔÚº¯ÊýÄÚÖ´ÐÐÈ«¾Ö´úÂ롣ΪÁË˵Ã÷Õâ¸öÎÊÌ⣬ÏÈ¿´Ò»¸öÀý×Ó£º
var s='global'; //¶¨ÒåÒ»¸öÈ«¾Ö±äÁ¿
function demo1(){
eval('var s="local"');
}
demo1();
alert(s); //->global
¸´ÖÆ´úÂë
ºÜºÃÀí½â£¬ÉÏÃæµÄdemo1º¯ÊýµÈ¼ÛÓÚ£ºfunction demo1(){var s='local';}£¬ÆäÖж¨ÒåÁËÒ»¸ö¾Ö²¿±äÁ¿s¡£
ËùÒÔ×îºóµÄÊä³öÊÇglobal²¢²»ÊÇʲôÆæ¹ÖµÄÊÂÇ飬±Ï¾¹´ó¼Ò¶¼ÄܺÜÇå³þµÄÇø·Ö¾Ö²¿±äÁ¿ºÍÈ«¾Ö±äÁ¿¡£
×ÐϸÌå»áһϣ¬¿ÉÒÔ·¢ÏÖevalº¯ÊýµÄÌص㣬Ëü×ÜÊÇÔÚµ÷ÓÃËüµÄÉÏÏÂÎıäÁ¿¿Õ¼ä£¨Ò²³ÆΪ£º°ü£¬closure£©ÄÚÖ´ÐУ¬ÎÞÂÛÊDZäÁ¿¶¨Ò廹ÊǺ¯Êý¶¨Ò嶼ÊÇÈç´Ë£¬ËùÒÔÈçϵĴúÂë»á²úÉúº¯Êý䶨ÒåµÄ´íÎó£º
var s='function test(){return 1;}'; //Ò»¸öº¯Êý¶¨ÒåÓï¾ä
function demo2(){
eval(s);
}
demo2();
alert(test()); //->error:test is not defined
¸´ÖÆ´úÂë
ÕâÊÇÒòΪtestº¯ÊýÔÚ¾Ö²¿¿Õ¼ä¶¨Ò壬demo2º¯ÊýÄÚ¿ÉÒÔ·ÃÎʵ½£¬ÍâÃæ¾Í·ÃÎʲ»µ½ÁË¡£
¶øÔÚʵ¼ÊµÄAjax¿ª·¢ÖУ¬ÓÐʱÎÒÃÇÐèÒª´Ó·þÎñÆ÷¶¯Ì¬»ñÈ¡´úÂëÀ´Ö´ÐУ¬ÒÔ¼õÇáÒ»´ÎÔØÈë´úÂë¹ý¶àµÄÎÊÌ⣬»òÕßÊÇһЩ´úÂëÊÇͨ¹ýJavascript×ÔÉíÉú³ÉµÄ£¬Ï£ÍûÓÃevalº¯ÊýÀ´Ê¹ÆäÖ´ÐС£
µ«ÕâÑùµÄ¶¯Ì¬»ñÈ¡´úÂëµÄ¹¤×÷Ò»°ãÔÚº¯ÊýÄÚÍê³É£¬±ÈÈ磺
function loadCode(){
var code=getCode();
eval(code);
}
¸´ÖÆ´úÂë
¿É¼ûeval²»¿ÉÄÜÔÚÈ«¾Ö¿Õ¼äÄÚÖ´ÐÐ
Ïà¹ØÎĵµ£º
±¾ÎÄÖ÷ÒªÊdzöÓÚÓÐÅóÓÑʹÓÃÎÒÔÀ´Ð´µÄautocompleteµÄJS¿Ø¼þ¡£µ±Êý¾ÝÁ¿´óµÄʱºò£¬»á³öÏÖЧÂʼ«ÆäÂýµÄÇé¿ö£¬ÎÒÔÚÕâ¶Îʱ¼ä×ö³öµÄһЩ²âÊÔÒ²¼°Ò»Ð©¾Ñ飬Óë´ó¼Ò·ÖÏí£¬Èç¹ûÓдíµÄµØ·½£¬»¹ÇëÖ¸³ö¡£
¾¹ý²âÊÔ£¬ÎÒÃǻᷢÏÖÈçϵÄÇé¿ö»òÕß˵µÄ½áÂÛ£¬Èç¹ûÄúµÄ²âÊÔ½á¹ûÓëÎҵIJ»·û£¬Çë˵Ã÷ÔÒò£¬ÒÔ±ãÏ໥ѧϰ¡£
1£©µ±Ò»¸ö½Ï´óµÄHTML×Ö· ......
function RegExpTest(){
var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion());
alert("version=="+ver);
if (ver >= 5.5){ // ²âÊÔ JScript µÄ°æ±¾¡£
var src = "The rain in Spain falls mainly in the plain.";
var re = /\w+/g; // ......
<html>
<head>
<mce:script type = "text/javascript"><!--
function changetext()
{
var x = document.getElementById("list");
for (var i = 0;i < x.length;i++ )
{
if (x.options[i].selected)
{
document.getElemen ......
JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A Ja ......