i'm a super beginner in JS. I try to create a way to generate random unique number (between 0 and 10) by clicking on a button. I want that this number is delete from the array after appearing.
Thank you 🙏🏻
const btn = document.getElementById("btn");
const showNumber = document.querySelector("h2");
let allNumbers = [];
for (var i =1; i <= 10; i++){
allNumbers.push(i);
}
const randomNumber = btn.addEventListener('click',()=> {
let n = Math.floor(Math.random()*allNumbers.length+1);
showNumber.innerText = n;
});
if(allNumbers.indexOf(n+1) === n) {
allNumbers.splice(n-1,1);
};
I'm assuming that you want the button to be able to work multiple times, and that you must therefore be able to remove a number from the array no matter where it might be located, as their positions will shift as numbers are removed. You therefore have several problems:
To avoid the first problem, instead of choosing a random number from 1 to 10 to remove, select a random location in the array:
const index = Math.floor(Math.random() * allNumbers.length);
const n = allNumbers[index];
Then you can just remove that element by index:
allNumbers.splice(index, 1);
Also note that randomNumber
is not useful because addEventListener()
only ever returns undefined
.