Bar*_*ill 5 javascript arrays reduce sum
使用之前的问题作为基点,在此处提出。我正在尝试创建一个完整的二十一点游戏,但在创建一个保存 的键:值对的 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();
Run Code Online (Sandbox Code Playgroud)
如果我将该reduce()方法放在函数末尾,它将返回“handTotal 未定义”错误。
有没有一种方法可以延迟该reduce()方法的运行,或者有一种更有效的方法可以在抽出更多牌时将数组中的数字相加?我希望这是有道理的,如果需要更多说明,请告诉我。
任何见解将不胜感激。
Rob*_*sen 10
您可以将初始值传递给您的reduce()调用:
let handTotal = handCards.reduce(function(sum, value) {
return sum + value;
}, 0);
// ^
// Initial value
Run Code Online (Sandbox Code Playgroud)
至于每次将牌添加到手牌时更新总数:为什么不添加一个方法来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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8543 次 |
| 最近记录: |