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);
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.
arr.length += 1
2.1m questions
2.1m answers
60 comments
57.0k users