简体   繁体   中英

Why does this function return undefined but console.logs the correct answer?

I have this function

 const getMonthlyPriceFromData = (planName) => {
    planTypeData.map((item) => {
      if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
        return item.monthlyFee;
      }
      return null;
    });
  };

when I console.log(item.monthyFee) it returns the correct answer but when I call

console.log(getMonthlyPriceFromData('Free')) it returns undefined?

There is no actual return statement inside your function:

  const getMonthlyPriceFromData = (planName) => {
    return planTypeData.map((item) => {
      if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
        return item.monthlyFee;
      }
      return null;
    });
  };

Or use short arrow form . This way you can omit the return keyword, only if you skip the curly braces too { :

  const getMonthlyPriceFromData = (planName) => planTypeData.map((item) => {
      if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
        return item.monthlyFee;
      }
      return null;
    })

EDIT:

OP seems to want only one item retuned from the array and for that find() would be a better approach:

const getMonthlyPriceFromData = (planName) => planTypeData.find((item) => {       
if (item.name === planName) { console.log(item.monthlyFee, 'fee')         
return true;       }       
return false;     })

You need to add a "return" before "planTypeData.map", like this:

 const getMonthlyPriceFromData = (planName) => {
     return planTypeData.map((item) => {
         if (item.name === planName) {
             return item.monthlyFee;
         }
         return null;
     });
 };


 console.log(getMonthlyPriceFromData('Free'))

Then it should work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM