问题描述:

I have an array of objects and I want to loop in throught once. This is the code of javascript.

 data.projectModelList.sum = function (prop) {

var total = 0;

for (var i = 0, _len = this.length; i < _len; i++) {

total += this[i][prop];

}

return total;

}

vm.dataTotal = [data.projectModelList.sum("budget"),

data.projectModelList.sum("tax"),

data.projectModelList.sum("money"),

data.projectModelList.sum("balance"),

data.projectModelList.sum("amount"),

data.projectModelList.sum("current"),

data.projectModelList.sum("after"),

data.projectModelList.sum("discount")]

When I loop through I get budget, tax, money, balance, amount, current, after, discount more than 1. I just wanna loop it through and then the result must be every item display once and not more. I know I need to change something in the for loop but I don't know what.

Kind regards

EDIT:

ModelItem

 public class ProjectDashBoardModel

{

public decimal budget { get; set; }

public decimal tax{ get; set; }

public decimal money{ get; set; }

public decimal balance{ get; set; }

public decimal amount{ get; set; }

public decimal current{ get; set; }

public decimal after{ get; set; }

public decimal discount{ get; set; }

}

public class ProjectDashboard

{

public Guid Id { get; set; }

public string ProjectLogo { get; set; }

public string LastMutatedBy { get; set; }

public DateTime LastMutatedDate { get; set; }

public List<ProjectDashBoardModel> ProjectModelList { get; set; }

}

网友答案:

You could change your sum function to return an object with all the sums as properties - this means you'd only have to loop the array once.

data.projectModelList.sum = function (props) {
       var total = {};
       for (var i = 0, _len = this.length; i < _len; i++) {
         for(var j=0;j<props.length;i++){
          var prop = props[j];
          if(total[prop] === undefined){
              total[prop] = 0;
          }
          total[prop] += this[i][prop];
         }
       }
       return total;
    }

You would call it with an array of all the properties you want:

var sums = data.projectModelList.sum(['budget','tax','money']);

And then you would read the sum using dot or bracket notation

var budgetTotal = sums.budget;
var moneyTotal = sums['money'];
相关阅读:
Top