简体   繁体   中英

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:} .

I am trying to add together the numbers in the cards[] array dynamically using the reduce() method but running into issues. Since the cards haven't been dealt yet, I get the error: Reduce of empty array with no initial value at 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.

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? 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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