为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥6287543 2021-05-07 14:13:29
我正在尝试通过实现一些功能来获取给定年份的最大心率。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 replicatefunction 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'”。显然,我尝试实现的代码被注释掉以产生结果。任何帮助表示赞赏。
查看完整描述

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);


查看完整回答
反对 回复 2021-05-27
  • 2 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信