Calling javascript function with an objectstring in dot notation

前端 未结 3 1626
灰色年华
灰色年华 2021-02-20 17:14

Suppose I have the string:

var string = \"function\";

With

window[string];

I can call a function with the nam

3条回答
  •  甜味超标
    2021-02-20 17:39

    you can split the string across . by using the String.split method:

    var string2 = "function.method.weHaveTogoDeeper";
    var methods = string2.split(".");
    

    In this examples, methods will be the array ["function","method","weHaveTogoDeeper"]. You should now be able to do a simple iteration over this array, calling each function on the result of the previous one.

    Edit

    The iteration I had in mind was something like this:

    var result = window;
    for(var i in methods) {
        result = result[methods[i]];
    }
    

    In your example, result should now hold the same output as

    window["function"]["method"]["weHaveTogoDeeper"]
    

提交回复
热议问题