0

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

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

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++;           
        }
    }
4

2 回答 2

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) {
于 2012-09-23T15:03:22.800 回答
0

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

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

于 2012-09-23T14:57:31.413 回答