1

so I created this script to generate an array of 5 random numbers where the numbers must be unique, but I get +2 undefined elements. There are 5 numbers which are unique but the length of the array isn't anymore 5

let arr = [];
while (arr.length <= 5) {
  let x = Math.floor(Math.random() * 11);
  if (arr.includes(x) === false) {
    arr.push(x);
  }
  arr.length += 1;
}
console.log(arr);

Thanks in advance guys.

Barmar
  • 741,623
  • 53
  • 500
  • 612
makar0v
  • 152
  • 6

3 Answers3

2

You should remove the arr.length += 1 line. The array length will be automatically incremented each time a new element is pushed, no need to modify it by yourself: this is a bad practice.

1

the length is not 5 because this loop runs 6 times, arr.length = 0,1,2,3,4,5. and you have a 3 undefined elements because of ( arr.length += 1; ) this skips step 1,3,5.

Am Ben
  • 89
  • 5
0

let arr = [];   
while (arr.length<5){
 let x = Math.floor(Math.random()*11);
 if (arr.includes(x) === false){
     arr.push(x);
}
}
console.log(arr);