[英]JavaScript: Use forEach within higher order function to manipulate / add to each element in array Error: undefined return
[英]JavaScript: Higher Order Function that Calls Add Function to Return New Array; Error: 'NaN' elements in output array
我有一个“有时”功能,想从中返回一个功能对象。
下面是我的代码:
let add = (a, b) => {
return a + b;
};
myFunc = sometimes(add);
const outputArr = [];
for (let i = 0; i < 3; i++) {
outputArr.push(myFunc(2 + i, 3 + i));
}
function sometimes (inputFunc){
return function (a, b){
return inputFunc()
}
}
outputArr
我期望我的outputArr变量等于:
[5, 7, 9]
相反,我等于:
[ NaN, NaN, NaN ]
我究竟做错了什么?
您没有将参数传递给包装的函数。 add
函数尝试对两个undefined
值求和,结果为NaN
(不是数字)。
您必须将参数传递给包装函数:
return function(a, b) {
return inputFunc(a, b); // <<<
}
由于sometimes
是一个高阶函数,需要包装不同的函数,并且参数数量会不断变化,因此无法知道包装函数的实现。 为了确保这一点,您应该使用rest参数 (将参数收集到数组中)并扩展 (将数组转换回参数)以将参数传递给包装的函数。
let add = (a, b) => { return a + b; }; myFunc = sometimes(add); const outputArr = []; for (let i = 0; i < 3; i++) { outputArr.push(myFunc(2 + i, 3 + i)); } function sometimes(inputFunc) { return function(...args) { return inputFunc(...args) } } console.log(outputArr);
您可以将代码用作
function sometimes(a,b){
return a + b;
}
const outputArr = [];
for (let i = 0; i < 3; i++) {
outputArr.push(sometimes(2 + i, 3 + i));
}
console.log(outputArr);
现在的输出是
[ 5, 7, 9 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.