嵌套for循环和备用映射方法

Nested for loop and alternate map method

本文关键字:映射 方法 备用 for 循环 嵌套      更新时间:2023-09-26

我是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);
};

我想在这里实现几件事。计算时应忽略nullNan值。我还想用mapreduce来实现这个计算。

我能看到的第一个问题是结果数组未初始化,因此结果将是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);