Javascript generate random unique number every time

后端 未结 7 1320
予麋鹿
予麋鹿 2021-01-15 16:25

Ok so i need to create four randomly generated numbers between 1-10 and they cannot be the same. so my thought is to add each number to an array but how can I check to see i

7条回答
  •  野的像风
    2021-01-15 16:40

    Here are a couple versions using Matt's grabBag technique:

    function getRandoms(numPicks) {
        var nums = [1,2,3,4,5,6,7,8,9,10];
        var selections = [];
    
        // randomly pick one from the array
        for (var i = 0; i < numPicks; i++) {
            var index = Math.floor(Math.random() * nums.length);
            selections.push(nums[index]);
            nums.splice(index, 1);
        }
        return(selections);
    }
    

    You can see it work here: http://jsfiddle.net/jfriend00/b3MF3/.

    And, here's a version that lets you pass in the range you want to cover:

    function getRandoms(numPicks, low, high) {
        var len = high - low + 1;
        var nums = new Array(len);
        var selections = [], i;
        // initialize the array
        for (i = 0; i < len; i++) {
            nums[i] = i + low;
        }
    
        // randomly pick one from the array
        for (var i = 0; i < numPicks; i++) {
            var index = Math.floor(Math.random() * nums.length);
            selections.push(nums[index]);
            nums.splice(index, 1);
        }
        return(selections);
    }
    

    And a fiddle for that one: http://jsfiddle.net/jfriend00/UXnGB/

提交回复
热议问题