在 javascript 中根据输入的字符串调用对应的函数?
阿神
阿神 2017-04-10 14:41:07
[JavaScript讨论组]

用户输入一个字符串(其实是函数的名字), 根据这个字符串调用对应的函数.

例如 输入 "hello"
调用 handle_hello 函数.

想做一个名字和函数的列表, 可是函数又不能做成指针, 怎么办?
而且存成什么格式 json? 数组?

阿神
阿神

闭关修行中......

全部回复(2)
ringa_lee

比如你有一个对象

var methods = {
    method1:function(){
        console.log('show me');
    },
    method2:function(){
        console.log('show me 2');
    }
}

//你可以这样执行他们,把函数名字做为一个字符串

methods['method1'](); //等同 methods.method1();
methods['method2'](); //等同 methods.method2();

如上,你就可以传字符串来执行函数了

var callFunction = function(methods,methodname){
     if(typeof methods[methodname] === 'function'){
         methods[methodname]();
     }
}
//todo
callFunction(methods,'method1');
天蓬老师
var functionMap = {
  handle_hello: function() {
  },
  handle_world: function() {
  }
};

var callFunction = function(obj, functionName) {
  obj["handle" + functionName]();
};

callFunction(functionMap, "hello");

是这样吗?

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号