如何在另一个函数中访问变量

时间:2011-07-26 17:40:14

标签: javascript

我正在为二十一点游戏编写代码并遇到了一些问题。我写了两个函数:一个用于初始交易,一个用于每个连续命中。这是交易功能:

var deck = [1,2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"];

function deal() {
var card1_val = Math.floor(Math.random() * deck.length);
var card2_val = Math.floor(Math.random() * deck.length);
var card1 = deck[card1_val];
var card2 = deck[card2_val];

var hand = card1 + ", " + card2;

{//card1 Conditionals
if (card1 == "Jack") {
    card1_val = 10;
    }
else if (card1 == "Queen") {
    card1_val = 10;
    }
else if (card1 == "King") {
    card1_val = 10;
    }
else if (card1 == "Ace") {
    card1_val = 11;
    }
}

{//card2 Conditionals
if (card2 == "Jack") {
    card2_val = 10;
    }
else if (card2 == "Queen") {
    card2_val = 10;
    }
else if (card2 == "King") {
    card2_val = 10;
    }
else if (card2 == "Ace") {
    card2_val = 11;
    }
}

var res = card1_val + card2_val;
document.getElementById("result").innerHTML = hand;
//document.getElementById("test").innerHTML = card1_val + ", " + card2_val;

if (res > 21) {
    alert("Blackjack!");
    }
}

这是命中功能:

function hit() {
var card_val = Math.floor(Math.random() * deck.length);
var nhand = deck[card_val];
bucket = hand + nhand
}

如果你看看hit()我正在使用来自deal()的var hand。我不能把它全局化,因为我每次都需要新的随机值。如何在不重写代码行的情况下访问同一个变量?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

你可以

  • 仅使用hand在功能范围之外声明var hand;并在hand函数中使用deal,而不将其重新声明为var;
  • 或在window.hand函数
  • 中声明hand时使用deal

答案 1 :(得分:0)

全局变量是邪恶的。我会采取更多面向对象的方法,比如这个

var Hand = function(bjcallback) {

    this.cards = [];

    this.onblackjack = bjcallback;

    this.deck = [1,2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"];

    this.values = {
        "Jack": 10,
        "Queen": 10,
        "King": 10,
        "Ace": 11
    };

    this.sum = function() {
        var i, x, res = 0;
        for (i in this.cards) {
            x = this.cards[i];
            if (typeof(x) != 'number') { x = this.values[x] };
            res += x;
        };
        return res
    };

    this.pick = function() {
        var pos = Math.floor(Math.random() * this.deck.length);
        var card = this.deck[pos];
        console.log(card);
        return card
    };

    this.deal = function(n) {
        n = n || 2;
        for (var i=0; i<n; i++) this.cards.push(this.pick())
    };

    this.hit = function() {
        this.cards.push(this.pick());
        if (this.sum() > 21) this.onblackjack();
    }
}

var hurray = function() { alert('Blackjack!') };
var hand = new Hand(hurray);

hand.deal();
hand.hit();

请注意,我不太喜欢卡片,所以我可能会混淆术语或计算