如何基于数组创建带参数的函数
我有一个数组,它可以简化函数的参数。
例如:
var params = ['name', 'age', 'email'];
此信息是由返回此数组的另一个端点创建的。从这个数组中,我想创建一个像这样的函数:
function (name, age, email) {
//...
//my custom code
return result;
}
正如你所看到的,我想自动创建函数并使用每个数组元素作为该函数的参数。
有没有办法在不使用eval
的情况下实现这一点?
看来 new Function('name', 'age', 'email', 'fn body') 也无法即时生成。
提前致谢
I have an array with would simbolize parameters of a function.
For Example:
var params = ['name', 'age', 'email'];
and this information is created by another endpoint which return this array. and from this array I would like to create a function like this:
function (name, age, email) {
//...
//my custom code
return result;
}
So as you can see I would like to automatically create functions and use each array element as an argument to that function.
Is there any way to achieve that without using eval
?
It seems new Function('name', 'age', 'email', 'fn body')
can't be generated on the fly as well.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不过,与 eval 相比,这没有具体的好处,并且您尝试做的事情可能会以不同的方式完成,而无需将字符串即时评估为代码
This has no concrete benefits over
eval
though and what you are trying to do could probably be done differently without needing to evaluate strings into code on the fly您可以使用
.apply()
。确保函数体是数组的最后一个成员。You can use
.apply()
. Make sure the function body is the last member of the array.如果要调用带有参数数组的函数,请使用
应用
。例如:If you want to call a function with an array of parameters, use
apply
. For example: