0

I want to create an array of four unique random numbers from 1-9 in JS. Code seems fine to me, but sometimes the numbers are not unique. Can someone please tell me what's wrong in my code? Thank you very much!

function randomNumbers() {
    var j =0;
    for (var i = 0; i < 4; i++) {
        numArr[i] = Math.floor(Math.random() * 9 + 1);
        if(i>0) {
            while (numArr[i] == numArr[j] && j != i) {
                numArr[i] = Math.floor(Math.random() * 9 + 1);
                if (numArr[i] != numArr[j]) {  
                    j++;  
                }
            }
        }
    }
}


Netta
  • 11
  • 2
  • when i try to run your sample code, i get a thrown `ReferenceError` because `numArr` is not defined. – r3wt Apr 11 '20 at 19:56
  • The way i would approach it is totally different, and i could not decipher what you were trying to do in your code, so i just posted an example of how i would approach the problem to jsbin -> https://jsbin.com/womuyebuga/edit?js – r3wt Apr 11 '20 at 20:05
  • @r3wt numArr is defined outside the function. i just didnt copy that part. i saw your code, but the numbers are no unique, just random... – Netta Apr 12 '20 at 19:14

0 Answers0