JS:在while循环中获取x个随机数

时间:2017-02-13 17:51:37

标签: javascript while-loop

我正在制作有六种可用套装的纸牌游戏,但是可以有2-6名玩家,我只想要与玩家数量匹配的套装数量。

let players = 4    
const suits = [1, 2, 3, 4, 5, 6]

当然,我希望他们随机出来。

我提出了以下解决方案:

export function getRandomSuits(nrOfPlayers) {
    const rangeMin = 1;
    const rangeMax = 6;
    const amount = nrOfPlayers;
    let nums = [];

    let getRandomNumber = function() {
        return Math.floor((Math.random() * rangeMax) + rangeMin);
    }

    while (nums.length < amount) {
        let nr = getRandomNumber();
        var numberExists = _.indexOf(nums, nr);
        console.log(numberExists);
        if(numberExists < 0) {
            nums.push(nr);
        }
    }

    return nums;
}

我使用&#34; while循环&#34;已经有一段时间了。好事,所以我对它感觉不舒服。

我的问题是:

  1. 这是一个好的做法还是有更好的解决方案?
  2. 为什么这个解决方案不好有任何性能或其他实际原因?
  3. 我是否过度思考?

1 个答案:

答案 0 :(得分:1)

  1. 在我看来,我认为不需要函数{ type: 'checkbox', name: 'Keywords', message: 'Please select the keywords you would like to use with a maximum of 5.', choices: NewDescriptionKeys } 。尽管如此,这取决于偏好。
    我会选择:

    getRandomNumber()
  2. 不一定。仅仅是清洁和偏好的问题。

  3. 也许? : - )
  4. 使用临时数组的第二种方法(稍微好一些):

    export function getRandomSuits(nrOfPlayers) {
        const rangeMin = 1;
        const rangeMax = 6;
        let nums = [];
    
        while (nums.length < nrOfPlayers) {
            let nr = Math.floor((Math.random() * rangeMax) + rangeMin);
            var numberExists = _.indexOf(nums, nr);
            if(numberExists < 0) {
                nums.push(nr);
            }
        }
    
        return nums;
    }
    
相关问题