您的位置:首页 > Web前端 > JavaScript

动态执行 javascript 函数

2016-05-24 17:13 246 查看
<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>无标题文档</title>

<script>

//动态执行函数:

function g1(){return 21;}

function g2(){return 22;}

function g3(){return 23;}

function g4(){return 24;}

function g(a){return a()};

function f(i) { return g(eval("g"+i)); }

document.write(f(1)+";"); //21

document.write(f(2)+";"); //22

document.write(f(3)+";"); //23

document.write(f(4)+";"); //24

</script>

</head>

 <body>

 </body>

</html>

以下为改进后的,当函数没有定义时,返回: No Function!

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>无标题文档</title>

<script>

//动态执行函数:

function g1(){return 21;}

function g2(){return 22;}

function g3(){return 23;}

function g4(){return 24;}

function g(a){

return a();

};

function f(i) { try{return g(eval("g"+i+""));} catch(e){return "NoFunction!";};}

document.write(f(0)+";"); //NoFunction!

document.write(f(1)+";"); //22

document.write(f(2)+";"); //24

document.write(f(3)+";"); //26

document.write(f(4)+";"); //28

</script>

</head>

 <body>

 </body>

</html>

动态执行函数时,不能像:

if(typeof(var1)=='undefined') alert('var1未定义');else alert('定义过了');

这样来检测 函数是否定义!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: