select random value NOT in array

后端 未结 5 941
渐次进展
渐次进展 2021-01-20 07:56

How would I select a random value (0 to 30) that is not in this array?

var list = new Array(1,3,4,7,8,9);
5条回答
  •  滥情空心
    2021-01-20 08:14

    You need a while loop that tests if rand is in your restricted array and, if so, re-generate a new random number:

    var rand;
    do {
        rand = Math.floor(Math.random() * 31); // re-randomize, 0 to 30 inclusive
    } while ($.inArray(rand, restricted) > -1);
    return rand;
    

    http://jsfiddle.net/mblase75/dAN8R/

    Don't want jQuery? You can replace $.inArray(rand, restricted) with restricted.indexOf(rand) if you use this polyfill for old browsers.

提交回复
热议问题