JS中如何使用动态名称调用函数

Gui*_*sos 2 javascript canvas

我试图按照我在下面发布的相同示例将其称为函数。所以问题是我用来调用函数的方法不起作用...我需要类似的东西,因为我将通过监听事件来调用这些函数。有人知道立即采取行动吗?

谢谢。

//variables
var ta = 3213;
var da = 44;
var s = [];

//Create string representation of function
s[1] = "function test0(){  alert(" + da + "); }";
s[0] = "function test1(){  alert(" + ta +"); }";

//"Register" the function
for(i=0; i< s.length; i++){
	eval(s[i]);
}

// calling the function
this["test"+1];
Run Code Online (Sandbox Code Playgroud)

bin*_*dMe 7

通常我们应该避免 eval。您想要做的事情也可以不使用 eval 并且使用更简单的代码:

//variables
var ta = 3213;
var da = 44;
var s = [];

//Create string representation of function
s[1] = function test0(){  alert(" + da + "); };
s[0] = function test1(){  alert(" + ta +"); };

s.forEach((fun) => { this[fun.name] = fun;});

// calling the function
this["test"+1]();
Run Code Online (Sandbox Code Playgroud)

或者在您的代码中简单地执行以下操作:

this["test"+1]();
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您使用 string 和 eval 只是因为您将函数名称作为字符串获取,那么您可以创建一个对象:

var data = {};
for(var i = 0; i<10; i++) {
  data['key'+ i] = function (i) { alert(i); }.bind(null, i);
}
Run Code Online (Sandbox Code Playgroud)