使用 reduce 获取 javascript 中数组中所有数字的总和
Using reduce to get sum of all numbers in an array in javascript
以上一个问题为基点,问。我正在尝试创建一个完整的二十一点游戏,并且 运行 遇到了创建一个 Hand 对象的问题,该对象包含 key:value 对 {name: cards[]: total: status:}
。
我正在尝试使用 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()
方法放在函数的末尾,它会 returns 一个 "handTotal is not defined" 错误。
有没有一种方法可以将 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;
}
以上一个问题为基点,问{name: cards[]: total: status:}
。
我正在尝试使用 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()
方法放在函数的末尾,它会 returns 一个 "handTotal is not defined" 错误。
有没有一种方法可以将 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;
}