javascript - 使用其名称作为字符串调用函数并使用数组替换参数
问题描述
这是我的示例,可以更好地理解我的问题。让我们说:
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 不是一个函数。请注意,我的主要目标不是连接字符串。这只是一个例子。我希望能够用任何功能做到这一点......
谢谢你
解决方案
You can use the []
syntax together with the spread operator ...
.
var a = ["Hello", "World"];
var b = "Hi";
console.log(b["concat"](...a));
推荐阅读
- bash - 从文本文件中添加多行后插入 4 个空格
- html - 如何更改 a 的返回类型
- jenkins-pipeline - docker npm build后Jenkins复制文件错误
- unity3d - 警告 CS0642,可能是错误的空语句
- node.js - AdonisJS 无法在函数内返回响应(SAP HANA)
- angular - Angular - mat-autocomplete 到 mat-select-search
- flutter - 隐藏溢出颤动,没有溢出消息
- reactjs - 如何遍历 MongoDB 条目,总结条目并呈现在 React 前端
- elasticsearch - 是否支持星号以外的 ElasticSearch 索引模式通配符?
- keras - 如何在 Keras 更改 ImageDataGenerator 的预处理函数执行顺序?