动态执行 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('定义过了');
这样来检测 函数是否定义!!
<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('定义过了');
这样来检测 函数是否定义!!
相关文章推荐
- javascript之BOM编程Screen(屏幕)对象
- javascript之BOM编程Screen(屏幕)对象
- JS七种加密解密方法
- javascript之BOM地址栏对象(Location)
- javascript之BOM地址栏对象(Location)
- pdfjs 实现预览服务器上的 PDF
- js的事件属性方法一览表
- 面向对象的JavaScript-008-Function介绍
- JSON解析
- javascript之BOM事件注册和案例
- javascript之BOM事件注册和案例
- javascript jsscript .js xml html json soap
- net.sf.json.JSONException: Unquotted string "E44C2B0168A550F6503F59CCD56FC49B"
- 对JavaScript 中数组用法的总结
- JSP中如何自己写分页
- FK JavaScript之:ArcGIS JavaScript添加Graphic,地图界面却不显示
- JSON详解
- 异步加载的JS如何在chrome浏览器断点调试?
- jsp常用标签
- JavaScript学习