javascript - 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?
解决方案
此问题的解决方案是使用不同的变量名称来保存 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
在声明箭头函数时使用。它有助于使功能不可操作
推荐阅读
- c# - 如何从邮递员“获取新的访问令牌”调用中生成代码片段
- python - 经过一段时间后中止循环
- php - 在 2Checkout 沙盒中测试定期付款
- css - 为什么我的边距会自动调整以使宽度相等?
- java - 打开 RAD 时出现 Spring 相关 XML 文件错误
- r - 如何根据两个变量之间的时间范围添加新的夜间/白天变量
- macos - 带有视网膜显示的 MacOS 上的 kivy 中的 UI 缩放
- css - Bootstrap 4中心和中间对齐表单元素
- wordpress - 如何在 Wordpress 中为多站点设置多个 TLD
- c# - 如何检查 PowerPoint 幻灯片是否包含图像