首页 > 解决方案 > Why is it saying that calcAverage is not a function, when it is

问题描述

I created a simple function to calcluate the average of 3 numbers:

let calcAverage = (v1,v2,v3) =>{

calcAverage = v1+v2+v3 / 3;

return calcAverage
}

const d1 = calcAverage(44, 23,71)
const k1 = calcAverage(44, 23,71)
console.log(d1)

if you comment out: const k1 = calcAverage(44, 23,71)then you will notice that the const d1 = calcAverage(44, 23,71)works, but why does it say 'Uncaught TypeError: calcAverage is not a function for this line of code: const k1 = calcAverage(44, 23,71)? this doesn't make any sense to me. how do I make both of them work? and why is it even saying that calcAverage is not a function i the first place?

标签: javascriptfunction

解决方案


此问题的解决方案是使用不同的变量名称来保存 calcAverage 箭头函数内的计算值。

let calcAverage = (v1,v2,v3) =>{

   let calcValue = (v1+v2+v3) / 3;
   // it is recommended you bracket your numerator so as not to confuse the calcuation
   // because leaving it as v1+v2+v3 / 3 will solve the maths as v1+v2+(v3/3)

   return calcValue;
}

const d1 = calcAverage(44, 23,71);
const k1 = calcAverage(44, 23,71);
console.log(d1)

至于我,我确实建议你const在声明箭头函数时使用。它有助于使功能不可操作


推荐阅读