Javascript全局变量不起作用

时间:2012-04-19 02:04:15

标签: javascript global-variables

我在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。我做错了什么?

6 个答案:

答案 0 :(得分:3)

您正在定义一个名为randSuit的全局变量,但一个具有相同名称的局部变量。执行randSuit = randSuit;时,实际上没有任何反应,因为左侧和右侧都引用了局部变量。你需要以不同的方式命名它们。

答案 1 :(得分:3)

@Elliot Bonneville和@jfriend00的答案很好,但这里有一些关于你的本地和全局变量问题背后理论的解释。

JavaScript处理全局变量和局部变量的方式是,当解释器遇到标识符时,它会在当前作用域中搜索它(在您的情况下为getRandCard),如果它找不到它 - 解释器上面有一个范围,如果在那里找不到它,那么上面有两个范围,依此类推。

randSuit = randSuit;

在这一行中,这些标识符都将引用相同的局部变量,因为解释器在本地范围内都找到它们,所以这条线路无效。

为了引用全局变量,您应该创建对其范围的引用:

var randSuit;
var that = this;    

function getRandCard() {
    ...
}

然后,替换:

randSuit = randSuit;

使用:

that.randSuit = randSuit;

答案 2 :(得分:2)

您在函数内重新声明了randSuit;该声明隐藏了全局randSuit,因此您的函数正在修改自己的局部变量而不是全局变量。

答案 3 :(得分:1)

当您在函数内重新声明randsuit时,它会被私有化到该函数

var randSuit = 5; // not shared
function getRandCard() {
    var randSuit = 3; // not shared
    console.log(randSuit);
}
getRandCard();
console.log(randSuit);

http://jsfiddle.net/PbBph/

如果您想共享randSuit的输出,请不要重新声明变量

var randSuit = 5; // shared
function getRandCard() {
    randSuit = 3; // shared
    console.log(randSuit);
}
getRandCard();
console.log(randSuit);

http://jsfiddle.net/PbBph/1/

更好的选择是模块化卡片变量和方法

var cardStack = (function () {
   var randSuit; // protected from global

   return {
      getRandSuit: function () { return randSuit; }, // but still readable
      getRandCard: function () { .... }
   };

}());

var card = cardStack.getRandCard();
    suit = cardStack.getRandSuit();

答案 4 :(得分:0)

试试这个,它是你的代码的缩短版本,应该可以工作:

var randSuit;
function getRandCard() {
    var randNum, randVal;

    var upperCards = ["Jack", "Queen", "King", "Ace"];
    var suits = ["Hearts", "Clubs", "Spades", "Diamonds"];

    randNum = Math.floor(Math.random()*13)+1;
    (randNum < 10) ? randVal++ : randVal = upperCards[randNum-10];

    randSuit = suits[Math.floor(Math.random()*4)];

    // return the value of the randomly chosen card.
    return (randVal + " of " + randSuit);
}

我使用了一些数组和一个三元运算符来大大缩短代码。我还删除了不受约束的本地randSuit变量,该变量是作用域并覆盖了您的全局对象。

答案 5 :(得分:0)

如果要使用全局变量,则全局定义变量,不要在本地重新定义,只需在本地使用即可。当您在本地重新定义它时,您将创建一个具有相同名称的新局部变量,该变量取代该范围中的全局变量。


其余部分实际上是评论,但由于我无法在评论中有效地包含代码,因此我会将其作为答案的一部分发布。您真的需要在代码中应用DRY(不要重复自己)原则。这非常重复:

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";
}

可以用这个重复性较低的代码替换:

var cards = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "Jack", "Queen", "King", "Ace"];
randVal = cards[Math.floor(Math.random() * cards.length)];

var suits = ["Hearts", "Clubs", "Spades", "Diamonds"];
randSuit = suits[Math.floor(Math.random() * suits.length)];