首页 > 解决方案 > 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);

标签: javascripthtmlvariables

解决方案


问题是你有这个cardSum:

var cardSum = cardNumber(cardOne, cardTwo);

这张卡片总和:

function inputValidation(cardSum) {

还有这张卡片:

var cardSum = moreCards(cardSum, extraCard);

您应该以不同的方式重命名它们,因为它们的含义不同。如果您找不到它们不同的名称,则将它们重命名为cardSum,_cardSum__cardSum.

这也挑战您识别您在哪里使用三个变量中的哪一个。为了良好的实践和干净的代码,如果两个变量在同一范围内可见,则永远不应将它们命名为相同。


推荐阅读