MyfunctionreturnsNaNandIdon´tknowwhy

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


以上是MyfunctionreturnsNaNandIdon´tknowwhy的全部内容。
THE END
分享
二维码
< <上一篇
)">
下一篇>>