用点符号的对象字符串调用javascript函数 [英] Calling javascript function with an objectstring in dot notation

查看:174
本文介绍了用点符号的对象字符串调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有字符串:

  var string =function; 

使用

 窗口[字符串]; 

我可以调用名称为function的函数。



但是,当我有:

  var string2 =function.method.weHaveTogoDeeper; 

应该调用

  window [function] [method] [weHaveTogoDeeper] 

我不能这样做:

  window [string2] 

在这种情况下。我不知道的数量。在字符串中,所以我需要某种例程。

解决方案

您可以将字符串拆分为。 通过使用 String.split 方法:

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

在这个例子中, methods 将会是数组 [function,method,weHaveTogoDeeper] 。你现在应该可以对这个数组做一个简单的迭代,对前一个结果调用每个函数。



编辑



我想到的迭代就是这样的:

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

$ / code>

在您的示例中, result 现在应该保持与
$ b

  window [function] [method] [weHaveTogoDeeper] 


Suppose I have the string:

var string = "function";

With

window[string];

I can call a function with the name of "function".

But, when I have:

var string2 = "function.method.weHaveTogoDeeper";

it should call

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

I can't do:

window[string2]

in this case. I dont know the number of "." in the string, so I need some kind of routine.

解决方案

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"]

这篇关于用点符号的对象字符串调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆