[英]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. 最后我使用了underscore.js的_.reduce
方法,但我没有在控制台中获得正确的数字。
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. 实际的点是10,12,18,3,0,0当我在console.log(sum)
得到0101218300,所以它将所有这些单独的数字变成一个巨大的数字,而不是通过添加总和而只是组合它们。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.