我是javascript的初学者,如果这个问题太简单,请耐心等待。我正在尝试简化这个功能
var calculateTotal =function(nodeData){
var totalSelectedUnit0 = 0;
var totalSelectedUnit1 = 0;
var totalSelectedUnit2 = 0;
for(x=$scope.selectFrom; x<$scope.selectTo; x++){
totalSelectedUnit0 += nodeData.items[0].usage.categories[x].current;
totalSelectedUnit1 += nodeData.items[1].usage.categories[x].current;
totalSelectedUnit2 += nodeData.items[2].usage.categories[x].current;
}
console.log(totalSelectedUnit0);
console.log(totalSelectedUnit1);
console.log(totalSelectedUnit2);
};
calculateTotal(node);
这就是我尝试重构代码的方式
var calculateTotal =function(nodeData){
var totalSelectedUnit=[];
for(i=0; i<nodeData.items.length; i++){
for(x=$scope.selectFrom; x<$scope.selectTo; x++){
totalSelectedUnit[i] += nodeData.items[i].usage.categories[x].current;
}
}
console.log(totalSelectedUnit);
};
我想在这里尝试一些事情。计算应忽略null
或Nan
值。另外,我想使用map
和reduce
来实现此计算。
答案 0 :(得分:0)
我可以看到的第一个问题是结果数组未初始化,因此当您向数字添加NaN
值时,结果将为undefined
。
var calculateTotal = function(nodeData) {
var totalSelectedUnit = nodeData.items.map(function(item) { //create a result value for each item in the items array
return item.usage.categories.slice($scope.selectFrom, $scope.selectTo).reduce(function(v1, v2) { //sum up values between the from and to index
return v1 + (v2 || 0); //ignore the falsy values
}, 0);
})
console.log(totalSelectedUnit);
};
var $scope = {
selectFrom: 0,
selectTo: 4
};
var nodeData = {
items: [{
usage: {
categories: [2, 3, 4, 5, 6, 7, 8, 9, 1]
}
}, {
usage: {
categories: [12, 13, 14, 15, 16, 17, 18, 19, 10]
}
}, {
usage: {
categories: [22, 23, 24, 25, 26, 27, 28, 29, 20]
}
}]
};
calculateTotal(nodeData);
&#13;