首页 > 解决方案 > 使用其名称作为字符串调用函数并使用数组替换参数

问题描述

这是我的示例,可以更好地理解我的问题。让我们说:

var a = ["Hello", "World"];
var b = "Hi";

我能怎么做:

console.log(b."concat"(a)); // and return HiHelloWorld

我试过这样做:

console.log(b.eval("concat").apply(this, a));

但它给了我一个错误,说 b.eval 不是一个函数。请注意,我的主要目标不是连接字符串。这只是一个例子。我希望能够用任何功能做到这一点......

谢谢你

标签: javascriptstringfunctionparameterseval

解决方案


You can use the [] syntax together with the spread operator ....

var a = ["Hello", "World"];
var b = "Hi";

console.log(b["concat"](...a)); 


推荐阅读