简体   繁体   中英

Addition of attributes backbone.js

homeTeam = this.collection.where({teamName: 'Bulls'});

var totalPoints = [];
_.each(homeTeam, function(team) {
    var total = team.get('points');
    totalPoints.push(total);
});

var sum = _.reduce(totalPoints, function(memo, num){ return memo + num; }, 0);
console.log(sum);

In the above I am trying to get the total amount of points the home team has, by iterating through that attribute, then pushing those values into an array. Finally I am using underscore.js's _.reduce method, but I am not getting the right number in the console.

The actual points are 10,12,18,3,0,0 and when I console.log(sum) I get 0101218300, so it turns all those seperate numbers into one gigantic number not by adding the sum but just combining them.

So obviously I am missing something, hopefully there is a better way to add attributes than the way I am doing it.

It's happening because total points is stored as an array of string. try

.each(homeTeam, function(team) {
    //convert the string to int
    var total = parseInt(team.get('points'),10);
    totalPoints.push(total);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM