简体   繁体   English

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

[英]Using reduce to get sum of all numbers in an array in javascript

Using a previous question as a base point, asked here . 以前面的问题为基点, 在此处询问。 I am trying to create a full Blackjack game and running into an issue with creating a Hand object that holds key:value pairs for {name: cards[]: total: status:} . 我试图创建一个完整的21点游戏,并遇到一个创建Hand对象的问题,该Hand对象持有{name: cards[]: total: status:} key:value对。

I am trying to add together the numbers in the cards[] array dynamically using the reduce() method but running into issues. 我正在尝试使用reduce()方法动态地将cards[]数组中的数字加在一起,但遇到了问题。 Since the cards haven't been dealt yet, I get the error: Reduce of empty array with no initial value at Array.reduce(). 由于尚未处理卡,因此出现错误:在Array.reduce()中没有初始值的情况下减少空数组。

Here is the code I have: 这是我的代码:

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();

If I place the reduce() method at the end of the function, it returns a "handTotal is not defined" error. 如果将reduce()方法放在函数的末尾,它将返回“未定义handTotal”错误。

Is there a way of either delaying the reduce() method to run after or a more efficient way of adding the numbers in the array together as more cards are drawn? 有没有一种方法可以延迟reduce()方法在运行之后运行,或者有一种更有效的方法来随着绘制更多卡而将数组中的数字相加? I hope this makes sense, if there is more clarification needed please let me know. 我希望这是有道理的,如果需要更多说明,请告诉我。

Any insights would be appreciated. 任何见解将不胜感激。

You could just pass an initial value to your reduce() call: 您可以将一个初始值传递给reduce()调用:

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

As far as updating the total every time a card is added to the hand: why don't you just add a method to Hand to add a card to it? 至于每次将卡片添加到手牌时都要更新总数:为什么不只是在Hand添加一种方法来向卡片中添加卡片呢? In the method you would just have to add the new card to the array and calculate the new total. 在该方法中,您只需要将新卡添加到阵列中并计算新总数即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM