猿问

如何在另一个函数中使用map函数和arrow函数?

我正在尝试通过实现一些功能来获取给定年份的最大心率。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'”。显然,我尝试实现的代码被注释掉以产生结果。任何帮助表示赞赏。


慕哥6287543
浏览 138回答 2
2回答

跃然一笑

您缺少从函数中返回值的方法,并且还应该从执行fn函数中返回值,而不是arr:function arrayCalc(arr, fn){&nbsp; const arrRes = arr.map(a => fn(a)); // and not .map(arr => arr)&nbsp; return arrRes; // missing return statement}工作示例:const years = [1990, 1965, 1937, 2005, 1998];// The function I'm trying to replicate/*function arrayCalc(arr, fn) {&nbsp; const arrRes = [];&nbsp; for (let i = 0; i < arr.length; i++) {&nbsp; &nbsp; arrRes.push(fn(arr[i]));&nbsp; }&nbsp; return arrRes;}*/// My attempt to shorten the arrayCalc function using .map and the arrowfunction arrayCalc(arr, fn){&nbsp; const arrRes = arr.map(a => fn(a));&nbsp; return arrRes;&nbsp; // OR&nbsp; // return arr.map(fn);}function calcAge(ex) {&nbsp; return new Date().getFullYear() - ex;}function maxHeartRate(ex) {&nbsp; const result_2 = Math.round(206.9 - (0.67 * ex))&nbsp; return (ex >= 18 && ex <= 81 ? result_2 : -1)}const ages = arrayCalc(years, calcAge);const heartRate = arrayCalc(ages, maxHeartRate);console.log(ages);console.log(heartRate);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答