gpt4 book ai didi

JavaScript 哈希值总和

转载 作者:行者123 更新时间:2023-12-03 08:41:28 25 4
gpt4 key购买 nike

我有以下对象;

  this.rolls = {1:[10], 2:[5,5], 3:[3,3], 4:[], 5:[],
6:[], 7:[], 8:[], 9:[],10:[]};

我目前无法在不得到“NaN”的情况下对该对象的值求和。我已经尝试了 $.eachif() 但没有成功。

有没有一种方法可以计算值而不得到“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com