我正在尝试通过实现一些功能来获取给定年份的最大心率。arrayCalc函数在名为“ arrRes”的空数组上使用for循环来推送新值。同时,calcAge函数根据当前年份计算一个人的年龄。我希望使用传递了一些参数的arrayCalc函数内部的.map和arrow函数,而不是for循环。我不知道该去哪里。
我尝试使用MDN网络文档之类的资源来阐明.map和arrow功能。一旦知道了它的语法及其实现,我便开始将.map和arrow函数包装到一个称为“ arrRes”的常量变量中。基本上,我正在尝试重现“旧” arrayCalc中给出的相同结果。
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(arry => arry);
} */
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);
我的输出应为// [29,54,82,14,21]。但是控制台给了我一个错误“未捕获的TypeError:无法读取未定义的属性'map'”。显然,我尝试实现的代码被注释掉以产生结果。任何帮助表示赞赏。
跃然一笑
相关分类