使用reduce来获取javascript中数组中所有数字的总和

时间:2017-10-11 04:58:27

标签: javascript arrays sum reduce

使用上一个问题作为基点,询问here。我正在尝试创建一个完整的Blackjack游戏并遇到一个问题,即创建一个Hand对象,该对象包含{name: cards[]: total: status:}的键:值对。

我正在尝试使用cards[]方法动态地将reduce()数组中的数字加在一起但遇到问题。由于卡尚未处理,我得到错误:在Array.reduce()中没有初始值的空数组减少。

这是我的代码:

function DrawOne() {
    let card = cardsInDeck.pop();
    return card;
}

function Hand(name, cards, total, status) {
    this.name = name;
    this.cards = [];
    this.total = total;
    this.status = status;
}

var playerHands = new Array();

function InitialDealOut() {
  ++handNumber;
  let newHand = 'playerHand0' + handNumber;
  let handCards = [];
  let handTotal = handCards.reduce(function(sum, value) {
      return sum + value;
  });

let playerHand = new Hand (newHand, handCards, handTotal, 'action');

p1 = DrawOne();
    handCards.push(p1.value);
p2 = DrawOne();
    handCards.push(p2.value);
}

InitialDealOut();

如果我将reduce()方法放在函数的末尾,则返回“handTotal is not defined”错误。

有没有一种方法可以延迟reduce()方法运行或者更有效的方法将数字添加到阵列中,因为绘制了更多的卡?我希望这是有道理的,如果需要更多说明,请告诉我。

任何见解都将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以将初始值传递给reduce()来电:

let handTotal = handCards.reduce(function(sum, value) {
    return sum + value;
}, 0);
// ^
// Initial value

每次将卡添加到手牌时更新总数:为什么不向Hand添加一个方法来添加卡?在该方法中,您只需将新卡添加到阵列并计算新总数。

function Hand(name, cards, total, status) {
    this.name = name;
    this.cards = [];
    this.total = total;
    this.status = status;
}

Hand.prototype.addCard = function(card) {
    this.cards.push(card);
    this.total += card.value;
}