我想计算所有旅行里程的总和。例如,50 + 70 + 20 = 140。
我尝试了以下代码,但所有返回的内容都是'NaN':
var totalmiles = car1.miles + car2.miles + car3.miles
这是我正在使用的代码:
var car1 = {type:"Holden", miles:50};
var car2 = {type:"Ford", miles:70};
var car3 = {type:"BMW", miles:20};
var cararray = [car1, car2, car3];
var totalmiles = car1.miles + car2.miles + car3.miles
console.log(totalmiles);
答案 0 :(得分:0)
你甚至不在这里使用数组。如果您将来需要使用该阵列,请尝试使用reduce
获得一个不错的单行解决方案。 for..of
循环也会起作用,但它会占用更多行。
var car1 = {type:"Holden", miles:50};
var car2 = {type:"Ford", miles:70};
var car3 = {type:"BMW", miles:20};
var cararray = [car1, car2, car3];
function getSumReduce(arr) {
// 0 is the starting value of "sum"
return arr.reduce((sum, car) => sum + car.miles, 0);
}
function getSumLoop(arr) {
var sum = 0;
for (var car of arr) {
sum += car.miles;
}
return sum;
}
console.log(getSumReduce(cararray));
console.log(getSumLoop(cararray));