javascript - JavaScript 变量值不继续
问题描述
我做了这个二十一点的程序,我不知道为什么,但是值“cardSum”最后没有加起来,基本上它只加了前两个卡值,我不知道为什么会这样。如果有人想帮忙,我的代码如下,谢谢。
function cardNumber(a, b) {
var cardTotal = a + b;
alert(`Your card numbers are ${a} and ${b}!`);
return cardTotal;
}
let cardRange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var cardOne = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardTwo = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardSum = cardNumber(cardOne, cardTwo);
function moreCards(a, b) {
alert(`Your extra card is ${b}!`);
var cardTotal = a + b;
return cardTotal;
}
function inputValidation(cardSum) {
var i;
for (i = 0; i < 3;) {
var input = prompt(`Which makes your card total ${cardSum}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null) {
window.location.replace("http://stackoverflow.com");
//take this back to home.html ^^^
i += 3;
}
else if (input === "1") {
i++;
var extraCard = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardSum = moreCards(cardSum, extraCard);
}
else if (input === "0") {
i += 3;
}
else {
alert("Wrong input, enter 1 or 0 on your keyboard!");
}
if (cardSum >= 22) {
i += 3;
}
}
}
function pontoonDecision(cardSum) {
var comScore = 18;
if (cardSum > comScore && cardSum < 22) {
document.write(`You got ${cardSum}, and the AI player got ${comScore}. Which means.... You win!`);
}
else if (cardSum === comScore) {
document.write(`You got ${cardSum}, and the AI player got ${comScore}. Which means.... It is a tie!`);
}
else if (cardSum >= 22) {
alert("BUST!");
document.write(`Your card number is ${cardSum}, which is above 21. Which means.... You lose!`);
}
else {
document.write(`You got ${cardSum}, and the AI player got ${comScore}. Which means.... You lose!`);
}
}
inputValidation(cardSum);
pontoonDecision(cardSum);
解决方案
问题是你有这个cardSum:
var cardSum = cardNumber(cardOne, cardTwo);
这张卡片总和:
function inputValidation(cardSum) {
还有这张卡片:
var cardSum = moreCards(cardSum, extraCard);
您应该以不同的方式重命名它们,因为它们的含义不同。如果您找不到它们不同的名称,则将它们重命名为cardSum
,_cardSum
和__cardSum
.
这也挑战您识别您在哪里使用三个变量中的哪一个。为了良好的实践和干净的代码,如果两个变量在同一范围内可见,则永远不应将它们命名为相同。
推荐阅读
- javascript - 更改 innerHTML 后如何在 textarea 上保留事件侦听器
- excel - Excel VBA - 范围偏移
- postgresql - 如何使用动态正则表达式匹配 Postgres 中的值
- python - 如何在 FloatLayout 中将圆形进度条与其累进数字一起移动?
- swift - 如何将部分 DragGesture 用于我的侧边菜单
- python-3.x - 如何将消息转发到具有干净范围的 Sentry(无运行时信息)
- python - 在 M1 芯片上编译 openCV 不会生成必要的文件
- google-sheets - Google 表格中的交叉引用(2 张具有不同长度列和可能重复的表格)
- sql-server - TSQL-如何在整个 .SQL 文件中缩写表名?
- python - 气流 Dag 对齐不正确