我对JavaScript相对较新,并且正在构建一个小应用程序,该应用程序从一组52张卡片中随机生成一张卡片(我将所有可能性存储在一个数组中)。但我要确保同一张卡不能生成两次。我无法找到一种方法。

var cardType = ["A♠","2♠","3♠","4♠","5♠","6♠","7♠","8♠","9♠","10♠","J♠","Q♠","K♠"];

function generateCard()
{
var card = cardType[Math.round(Math.random() * (cardType.length - 1))];
}


锹符号实际上不在我的数组中,我只是为了便于查看而将其放入。

最佳答案

预混洗阵列,然后一次从阵列中弹出一张卡

var cardType = ["A♠","2♠","3♠","4♠","5♠","6♠","7♠","8♠","9♠","10♠","J♠","Q♠","K♠"];

//shuffles array
cardType.sort(function() { return 0.5 - Math.random() });

function generateCard()
{
    return cardType.pop();
}


当您得到undefined时,意味着您已经获得了所有卡片

关于javascript - JavaScript从数组中删除值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17896330/

10-11 14:13