在数组内执行一个函数 [英] Execute a function inside array
本文介绍了在数组内执行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以从数组的内部执行匿名函数(也在数组内部定义)?
return [
//执行?
function(){
//逻辑
}
];
还是我应该在外部定义它,然后再调用它?
解决方案
从技术上讲,您可以将函数括在括号中并像这样调用它:
return [
(function(){return 42;})()
];
与
<$ p $相同p>
return [
42
];
但是,为什么要这样做?它只会使代码的可读性降低。最好只拥有一个单独的变量来保存闭包,然后根据需要调用它。
Is it possible to execute an anonymous function (also, defined inside the array) from inside the of the array ?
return [
//execute?
function() {
//logic
}
];
Or should I define it outside and only then call it?
解决方案
Technically, you can enclose the function in parentheses and invoke it like this:
return [
(function() { return 42; })()
];
which is the same as
return [
42
];
However, why would you want to do this? It will only serve to make the code less readable. It would be much better to simply have a separate variable that holds the closure and invoke that as required instead.
这篇关于在数组内执行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文