Calling javascript function with an objectstring in dot notation

前端 未结 3 1632
灰色年华
灰色年华 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

    function index(x,i) {return x[i]}
    string2.split('.').reduce(index, window);
    

    edit: Of course if you are calling functions from strings of their names, you are likely doing something inelegant which would be frowned upon, especially in a collaborative coding settings. The only use case I can think of that is sane is writing a testing framework, though there are probably a few more cases. So please use caution when following this answer; one should instead use arrays, or ideally direct references.

提交回复
热议问题