繁体   English   中英

为什么这个 function 返回 undefined 但 console.logs 正确答案?

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

我有这个 function

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

当我 console.log(item.monthyFee) 它返回正确的答案但是当我打电话时

console.log(getMonthlyPriceFromData('Free')) 它返回未定义?

function 中没有实际的return语句:

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

或使用短箭头形式 这样你就可以省略return关键字,只有当你也跳过花括号{

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

编辑:

OP 似乎只希望从数组中重新调整一个项目,因此find()将是一种更好的方法:

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

您需要在“planTypeData.map”之前添加一个“return”,如下所示:

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


 console.log(getMonthlyPriceFromData('Free'))

然后它应该工作!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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