扑克,询问我的卡是否已被使用

时间:2012-09-23 14:52:05

标签: javascript

我是一个JavaScript菜鸟,想知道是否有更好的方式来询问我的脚本是否已经使用了生成的卡片。

现在,我正在使用一堆运算符,但是,必须采用一种不那么冗余的方法。如果你们中的任何一个人能够回答我的问题,从长远来看,这对我真的有帮助。感谢

var cards = ['Ace of heart','Ace of club','Ace of diamond','Ace of spade',
                 'Two of heart','Two of club','Two of diamond','Two of spade',
                 'Three of heart','Three of club','Three of diamond','Three of spade',
                 'Four of heart','Four of club','Four of diamond','Four of spade',
                 'Five of heart','Five of club','Five of diamond','Five of spade'];

    // Distributed Cards //
    var pre_flop = [1];
    var flop = [2];
    var turn = [0];
    var river = [0];

    // Cards value //
    var your_card;
    var indexed_cards = [6];

    var total_card = 0;
    var deck_size = cards.length;       

    function generate_card(){

        // Assign value to first card //
        if(total_card === 0){
            your_card = Math.floor(Math.random() * deck_size);
            indexed_cards [total_card] = your_card;
            total_card++;
        }else{
            your_card = Math.floor(Math.random() * deck_size);
            // Makes sure the cards are different //
            while(1){
                if(your_card === indexed_cards [0] || your_card === indexed_cards [1] || your_card === indexed_cards [2] || your_card === indexed_cards [3] || your_card === indexed_cards [4] || your_card === indexed_cards [5] || your_card === indexed_cards [6]){
                    your_card = Math.floor(Math.random() * deck_size);
                }else {
                    indexed_cards [total_card] = your_card;
                    break;
                }
            }
            total_card++;           
        }
    }

2 个答案:

答案 0 :(得分:1)

回答有关更换OR的具体问题:

您可以使用array.indexOf(..)来确定某些内容是否在数组中。

var myarray = [1, 3, 77, 12, 9];

console.log('index of 77 ' + myarray.indexOf(77));    // 2
console.log('index of 4 ' + myarray.indexOf(4))    // -1

如果找不到项目,indexOf返回-1,否则返回项目在数组中的位置。您可能还看过在字符串上使用此方法,以查找字符串中字符的位置或存在;同样的原则适用于此。

可能存在代码的其他问题,但您应该能够替换

if(your_card === indexed_cards [0] || your_card === indexed_cards [1] || your_card === indexed_cards [2] || your_card === indexed_cards [3] || your_card === indexed_cards [4] || your_card === indexed_cards [5] || your_card === indexed_cards [6]){

if (indexed_cards.indexOf(your_card) !== -1) {

答案 1 :(得分:0)

基本上就是这样,你可以使用jquery array.contains或indexOf检查你是否想让它看起来更漂亮。

我假设6是indexed_cards数组的最大长度。