简体   繁体   中英

My function returns NaN and I don´t know why

I have written this code as an exercise. It is suppost to add up the amount paid for gas and food (stored in the arrays). Sadly I dont know why it returns 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);

You're trying to sum numbers with undefined.

let gasTotal = 0;
let foodTotal = 0;

Initializing as numbers will fix it

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