Blackjack游戏点击New card按钮时初始卡牌重复显示问题求助
问题修复:Blackjack游戏「New card」按钮重复显示卡牌
问题原因
- 重复渲染卡牌:在
newCard函数中,你直接在cardsEl原有文本后循环拼接整个cards数组的所有元素。由于cards数组已经包含了开局的两张牌,每次点击都会把所有牌再重复追加一遍,导致出现6 7 6 7 11这类重复内容。 - 条件判断错误:
if (isAlive = true && hasBlackJack === false)使用了赋值运算符=,而非比较运算符===,这会强制将isAlive设为true,无论之前的状态如何,属于逻辑bug。
修复方案
方案一:仅追加新卡牌(高效简洁)
既然新卡牌是数组最后一个元素,直接追加该元素即可,无需循环整个数组:
function newCard() { if (isAlive && hasBlackJack === false) { // 修复赋值为比较判断 let thirdCard = getRandomCard(); cards.push(thirdCard); sum += thirdCard; cardsEl.innerText += " " + thirdCard + " "; // 只追加新生成的卡牌 sumEl.innerText = "Sum: " + sum; if (sum <= 20) { message = "Do you want to draw a new card?" } else if (sum === 21) { message = "Wohoo! You've got Blackjack!"; hasBlackJack = true; } else { message = "You're out of the game!"; isAlive = false; } messageEl.innerText = message; } }
方案二:重新渲染所有卡牌(易维护,适配后续扩展)
和startGame逻辑保持一致,先重置cardsEl的文本内容,再重新遍历所有卡牌拼接:
function newCard() { if (isAlive && hasBlackJack === false) { // 修复赋值为比较判断 let thirdCard = getRandomCard(); cards.push(thirdCard); sum += thirdCard; cardsEl.innerText = "Cards: "; // 先重置初始文本 for (let i=0; i<cards.length; i++) { cardsEl.innerText += " " + cards[i] + " "; } sumEl.innerText = "Sum: " + sum; if (sum <= 20) { message = "Do you want to draw a new card?" } else if (sum === 21) { message = "Wohoo! You've got Blackjack!"; hasBlackJack = true; } else { message = "You're out of the game!"; isAlive = false; } messageEl.innerText = message; } }
内容的提问来源于stack exchange,提问作者Mo GRA
相关产品推荐
相关产品推荐

