Javascript哈希值的总和

时间:2015-10-09 11:11:08

标签: javascript

我有以下对象;

  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--;
  };
};

3 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:0)

对于数组内对象的每个结果:

var rolls = { 1:[10], 2:[5,5], 3:[3,3], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[],10:[] };
var results = Object.keys(rolls).map(function(key) {
  if (rolls[key].length) {
    return rolls[key].reduce(function(a,b) {
      return a + b;
    });
  } else {
    return 0;
  }
});

results = [10, 10, 6, 0, 0, 0, 0, 0, 0, 0]

答案 2 :(得分:0)

通过 对象。检查是否array length > 0。如果是这样,请通过 数组将每个值添加到结果中:

for (var key in obj) {
    if (obj[key].length > 0) {
        obj[key].forEach(function (el) {
            res += el;
        });
    }
}

Example