2 回答

TA贡献1826条经验 获得超6个赞
您缺少从函数中返回值的方法,并且还应该从执行fn函数中返回值,而不是arr:
function arrayCalc(arr, fn){
const arrRes = arr.map(a => fn(a)); // and not .map(arr => arr)
return arrRes; // missing return statement
}
工作示例:
const years = [1990, 1965, 1937, 2005, 1998];
// The function I'm trying to replicate
/*function arrayCalc(arr, fn) {
const arrRes = [];
for (let i = 0; i < arr.length; i++) {
arrRes.push(fn(arr[i]));
}
return arrRes;
}*/
// My attempt to shorten the arrayCalc function using .map and the arrow
function arrayCalc(arr, fn){
const arrRes = arr.map(a => fn(a));
return arrRes;
// OR
// return arr.map(fn);
}
function calcAge(ex) {
return new Date().getFullYear() - ex;
}
function maxHeartRate(ex) {
const result_2 = Math.round(206.9 - (0.67 * ex))
return (ex >= 18 && ex <= 81 ? result_2 : -1)
}
const ages = arrayCalc(years, calcAge);
const heartRate = arrayCalc(ages, maxHeartRate);
console.log(ages);
console.log(heartRate);
添加回答
举报