suchen

Heim  >  Fragen und Antworten  >  Hauptteil

在 javascript 中根据输入的字符串调用对应的函数?

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

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

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

阿神阿神2910 Tage vor393

Antworte allen(2)Ich werde antworten

  • ringa_lee

    ringa_lee2017-04-10 14:43:07

    比如你有一个对象

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    <code>var methods = {

        method1:function(){

            console.log('show me');

        },

        method2:function(){

            console.log('show me 2');

        }

    }

     

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

     

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

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

    </code>

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

    1

    2

    3

    4

    5

    6

    7

    8

    <code>var callFunction = function(methods,methodname){

         if(typeof methods[methodname] === 'function'){

             methods[methodname]();

         }

    }

    //todo

    callFunction(methods,'method1');

    </code>

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-04-10 14:43:07

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    <code>var functionMap = {

      handle_hello: function() {

      },

      handle_world: function() {

      }

    };

     

    var callFunction = function(obj, functionName) {

      obj["handle" + functionName]();

    };

     

    callFunction(functionMap, "hello");

    </code>


    是这样吗?

    Antwort
    0
  • StornierenAntwort