【发布时间】:2019-09-28 14:41:25
【问题描述】:
我试图通过实现一些函数来获得给定几年的最大心率。 arrayCalc 函数在一个名为“arrRes”的空数组上使用 for 循环来推送一个新值。同时,calcAge 函数从当前年份计算一个人的年龄。我希望在 arrayCalc 函数中使用 .map 和箭头函数,而不是 for 循环,这些函数传递了一些参数。我不知道该怎么做。
我尝试使用 MDN 网络文档等资源来阐明 .map 和箭头的功能。一旦我知道它的语法和实现,我就开始将 .map 和箭头函数包装到一个名为“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]。但是控制台给了我一个错误“Uncaught TypeError: Cannot read property 'map' of undefined”。显然,我试图实现的代码被注释掉以产生结果。任何帮助表示赞赏。
【问题讨论】:
标签: javascript function ecmascript-6 arguments arrow-functions