Javascript generate random unique number every time

后端 未结 7 1318
予麋鹿
予麋鹿 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:45

    Use an array to see if the number has already been generated.

    var randomArr = [], trackingArr = [],
        targetCount = 4, currentCount = 0,
        min = 1, max = 10,
        rnd;
    
    while (currentCount < targetCount) {
        rnd = Math.floor(Math.random() * (max - min + 1)) + min;
        if (!trackingArr[rnd]) {
            trackingArr[rnd] = rnd;
            randomArr[currentCount] = rnd;
            currentCount += 1;
        }
    }
    
    alert(randomArr); // Will contain four unique, random numbers between 1 and 10.
    

    Working example: http://jsfiddle.net/FishBasketGordo/J4Ly7/

提交回复
热议问题