[英]Sum the negative numbers of an array using reduce() in JavaScript
[英]Using reduce to get sum of all numbers in an array in javascript
以前面的問題為基點, 在此處詢問。 我試圖創建一個完整的21點游戲,並遇到一個創建Hand對象的問題,該Hand對象持有{name: cards[]: total: status:}
key:value對。
我正在嘗試使用reduce()
方法動態地將cards[]
數組中的數字加在一起,但遇到了問題。 由於尚未處理卡,因此出現錯誤:在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”錯誤。
有沒有一種方法可以延遲reduce()
方法在運行之后運行,或者有一種更有效的方法來隨着繪制更多卡而將數組中的數字相加? 我希望這是有道理的,如果需要更多說明,請告訴我。
任何見解將不勝感激。
您可以將一個初始值傳遞給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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.