我有以下对象;
this.rolls = {1:[10], 2:[5,5], 3:[3,3], 4:[], 5:[],
6:[], 7:[], 8:[], 9:[],10:[]};
我目前无法在不得到“NaN”的情况下对该对象的值求和。我已经尝试了 $.each
和 if()
但没有成功。
有没有一种方法可以计算值而不得到“NaN”?
这是我的代码;
function Game() {
this.score = 0;
this.frameOver = false;
this.rolls = {1:[], 2:[], 3:[], 4:[], 5:[],
6:[], 7:[], 8:[], 9:[],10:[]};
this.currentFrame = 1;
this.bonusManager = null;
this.bonusCounter = 0
};
Game.prototype.roll = function(pins) {
this.bonusChecker(pins);
this.rolls[this.currentFrame].push(pins);
this.bonusDistributor(pins);
this.frameChecker(pins);
};
Game.prototype.frameChecker = function(pins) {
if (pins === 10 || this.frameOver === true) {
this.currentFrame++; this.frameOver = !this.frameOver
} else {
this.frameOver = !this.frameOver;
}
};
Game.prototype.bonusChecker = function(pins) {
if (pins === 10) {
this.nextTwoBonus;
this.score +=10
};
var total = 0;
$.each(this.rolls[this.currentFrame],function() {
total += this
});
if (total === 10) {
this.nextOneBonus;
this.score += pins
}
this.score += pins
};
Game.prototype.nextTwoBonus = function() {
this.bonusCounter = 2;
this.bonusManager = this.rolls[this.currentFrame]
};
Game.prototype.nextOneBonus = function() {
this.bonusCounter = 1;
this.bonusManager = this.rolls[this.currentFrame]
};
Game.prototype.bonusDistributor = function(pins) {
if (this.bonusCounter != 0) {
this.bonusManager += pins;
this.bonusCounter--;
};
};
最佳答案
试试这个
var rolls = {1:[10], 2:[5,5], 3:[3,3], 4:[], 5:[],
6:[], 7:[], 8:[], 9:[],10:[]};
var sum = 0,
vals;
for (var k in rolls) {
vals = rolls[k];
for (var i=0; i<vals.length; i++) {
sum += vals[i] || 0;
}
}
alert(sum);
看到这个jsfiddle
关于JavaScript 哈希值总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33036797/