从数组映射到调用函数构造函数失败

时间:2018-12-14 17:49:17

标签: javascript arrays mapping

我需要做这样的事情:

Array.from(["xx","aa"], Function, this)

应该返回带有两个匿名函数的数组,如下所示:

[ function anonymous(){ xx }, function anonymous() { aa } ]

但是我得到的数组是:

[ function anonymous(xx){ 0 }, function anonymous(aa) { 1 } ]

我看了Array.from()的文档,似乎在映射数组时调用了callback(this[i], i, this),其中this是要映射的数组,i是当前元素索引。

我可以通过执行以下操作来限制发送的参数:

Array.from(["xx","aa"], function(elem) { Function(elem) } , this)[0]

但是,这将返回undefined并且不返回任何函数!

关于如何使其不使用以下语法发送数组索引的任何想法:Array.from(["xx","aa"], Function, this)[0]

谢谢。

1 个答案:

答案 0 :(得分:0)

我不确定您要实现什么目标,但是不能仅仅Array#map遍历那个数组吗?

const r = [() => 'foo', () => 'boo'].map((f) => () => f);

console.log(r);
r.forEach((f) => console.log(f()()));