How to choose a set of unique random numbers (no duplicates) using the jQuery.inArray method?

前端 未结 3 954
旧巷少年郎
旧巷少年郎 2020-12-21 04:07

This is a Javascript / jQuery question:

I\'m trying to generate six unique random numbers between 1 and 21 (no duplicates), using the jQuery.inArray

3条回答
  •  猫巷女王i
    2020-12-21 04:44

    The immediately obvious reason it's not working, other than the extra closing parenthesis after your while loop, is a slight misunderstanding on how $.inArray method works. $.inArray returns the first index of a matched value in the array, or -1 if it's not found. -1 is a "truthy" value, meaning your while loop will continue execution if the random number isn't in the array. In fact, it will continue execution until it finds the number at the 0th location of the array.

    In order to fix that particular problem, you need to check that it's greater than -1, as well as setting the x var to a random number before the loop:

    var x = Math.ceil(Math.random() * TotalLogos);
    
    while ($.inArray(x, r) > -1) {
        x = Math.ceil(Math.random() * TotalLogos);
    }
    r[t] = x;
    

    In the comment replies to your question, Pointy also mentions the Fisher-Yates Shuffle. That method of shuffling might give you better distribution than the approach you're using.

提交回复
热议问题