第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在另一個函數(shù)中使用map函數(shù)和arrow函數(shù)?

如何在另一個函數(shù)中使用map函數(shù)和arrow函數(shù)?

慕哥6287543 2021-05-07 14:13:29
我正在嘗試通過實(shí)現(xiàn)一些功能來獲取給定年份的最大心率。arrayCalc函數(shù)在名為“ arrRes”的空數(shù)組上使用for循環(huán)來推送新值。同時,calcAge函數(shù)根據(jù)當(dāng)前年份計(jì)算一個人的年齡。我希望使用傳遞了一些參數(shù)的arrayCalc函數(shù)內(nèi)部的.map和arrow函數(shù),而不是for循環(huán)。我不知道該去哪里。我嘗試使用MDN網(wǎng)絡(luò)文檔之類的資源來闡明.map和arrow功能。一旦知道了它的語法及其實(shí)現(xiàn),我便開始將.map和arrow函數(shù)包裝到一個稱為“ arrRes”的常量變量中。基本上,我正在嘗試重現(xiàn)“舊” arrayCalc中給出的相同結(jié)果。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);我的輸出應(yīng)為// [29,54,82,14,21]。但是控制臺給了我一個錯誤“未捕獲的TypeError:無法讀取未定義的屬性'map'”。顯然,我嘗試實(shí)現(xiàn)的代碼被注釋掉以產(chǎn)生結(jié)果。任何幫助表示贊賞。
查看完整描述

2 回答

?
躍然一笑

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個贊

您缺少從函數(shù)中返回值的方法,并且還應(yīng)該從執(zhí)行fn函數(shù)中返回值,而不是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);


查看完整回答
反對 回復(fù) 2021-05-27
  • 2 回答
  • 0 關(guān)注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號