我在 JavaScript 中遇到全局变量问题。我尝试做的是在函数外部声明变量,然后在函数内更改它,然后调用另一个函数。从我读过的内容来看,这应该有效,但它只是让我不确定。这是我正在制作的卡片绘图游戏的代码。
var randSuit;
function getRandCard() {
var randNum;
var randSuit;
var randVal;
randNum = Math.floor(Math.random()*13)+1;
if (randNum == 1) {
randVal = "2";
} else if (randNum == 2) {
randVal = "3";
} else if (randNum == 3) {
randVal = "4";
} else if (randNum == 4) {
randVal = "5";
} else if (randNum == 5) {
randVal = "6";
} else if (randNum == 6) {
randVal = "7";
} else if (randNum == 7) {
randVal = "8";
} else if (randNum == 8) {
randVal = "9";
} else if (randNum == 9) {
randVal = "10";
} else if (randNum == 10) {
randVal = "Jack";
} else if (randNum == 11) {
randVal = "Queen";
} else if (randNum == 12) {
randVal = "King";
} else if (randNum == 13) {
randVal = "Ace";
}
randNum = randNum = Math.floor(Math.random()*4)+1;
if (randNum == 1) {
randSuit = "Hearts";
} else if (randNum == 2) {
randSuit = "Clubs";
} else if (randNum == 3) {
randSuit = "Spades";
} else if (randNum == 4) {
randSuit = "Diamonds";
}
console.log(randSuit);
var randCard = (randVal + " of " + randSuit);
//Return the Value of the randomly chosen Card.
return (randCard);
}
//This function calls the random card from the function above, then applies logic to see if it's the same, then outputs the result.
$(function() {
$('#drawCard').click(function() {
var e = document.getElementById("faceValue");
var faceValue = e.options[e.selectedIndex].text;
var e = document.getElementById("suit");
var suit = e.options[e.selectedIndex].text;
$('#oneCardContainer').slideDown('slow');
var pickedCard = (faceValue + " of " + suit);
var randCard = getRandCard();
console.log (randSuit);
if (pickedCard == randCard) {
$("#oneCardResults").val("You Chose a " + pickedCard + " and got a " + randCard + ". \nYou Win!");
} else if (pickedCard != randCard) {
$("#oneCardResults").val("You Chose a " + pickedCard + " and got a " + randCard + ". \nYou Lose!");
}
});
});
那是我尝试过的代码,我尝试传递的变量是 randSuit。我究竟做错了什么?