【发布时间】:2022-01-09 16:08:09
【问题描述】:
我想创建一个返回函数数组的函数。调用数组中的任何函数时,结果必须是该函数在数组中的索引。任务和挑战是创建没有 for 循环的函数。我是这样移动的,但是代码没有按预期工作:
const createArrayOfFunctions = number => {
const functionsArray = new Array(number).fill();
return functionsArray.map(element => function() {
return functionsArray.indexOf(element);
});
};
我预计:
const testArray = createArrayOfFunctions(7);
testArray[2](); // 2;
有什么方法可以在不使用 for 循环的情况下实现目标。我需要它来完成一个学习项目。
【问题讨论】:
-
做一个
console.log(functionsArray)。您会注意到它仅包含undefined值。执行functionsArray.indexOf(element)将始终在索引0 处找到undefined。 -
您需要再次检查docs for the
mapmethod。无需使用indexOf来找出调用回调的索引!
标签: javascript arrays function methods return