繁体   English   中英

我的 function 返回 NaN 我不知道为什么

[英]My function returns NaN and I don´t know why

我写了这段代码作为练习。 假设将支付的汽油和食物(存储在数组中)的金额相加。 可悲的是,我不知道为什么它返回 NaN。

 const gas = [20, 40, 100]; const food = [10, 40, 50]; function total(gas, food) { let gasTotal; let foodTotal; for (i = 0; i < gas.length; i++) { gasTotal += gas[i]; } for (i = 0; i < food.length; i++) { foodTotal += food[i]; } const paidtotal = gasTotal + foodTotal; console.log(paidtotal); } total(gas, food);

您正在尝试将未定义的数字相加。

let gasTotal = 0;
let foodTotal = 0;

初始化为数字将修复它

暂无
暂无

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

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