Ad
How To Create An Unique And Random Number From An Array In Javascript
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);
};
Ad
Answer
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:
- The code that selects a random number to remove may choose a number that has already been removed.
- The code assumes that the number is at a particular position, which may not be true after the first removal.
- The code that removes the element from the array is currently located outside of the event listener that is invoked when you click the button; you must move it inside the function for it to work.
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
.
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad