JavaScript动态函数名称 [英] JavaScript dynamic function name

查看:95
本文介绍了JavaScript动态函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要动态地将函数的名称赋给关联数组的元素。这是我的尝试不起作用。我要求帮助的问题是我尝试调用函数: cr ['cmd1'](x);

I need to dynamically assign the name of a function to an element of an associative array. This is my attempt which does not work. The problem I am asking for help with is here where I try to call the function: cr['cmd1'](x);

<!DOCTYPE html>

<html>
<head>
    <script type="text/javascript">
        var cr =[];
        var x = 5;
        cr['cmd1'] ='foo';
        var msg = cr['cmd1'](x);  
        alert(msg);

        function foo(y){
            return y;
        }
    </script>
</head>
<body>
</body>
</html>

编辑:我在这里传递了一个字符串 cr ['cmd1'] ='foo'; 我无法控制。这就是为什么我必须使用字符串作为外部应用程序的起点。

I being passed a string here cr['cmd1'] ='foo'; that I cannot control. That is why I have to work with a string as a starting point from an external application.

推荐答案

使用此语法访问函数 window [function_name]('para1');

您的用法将是这样的

var msg = window[cr['cmd1']](x);

这篇关于JavaScript动态函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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