I am trying to make a function which returns a random number from among a set of specified numbers (comma seperated) in React. I mean,
randomInside(10,20,25,45) // desired output is one of the numbers, e.g. 25
My try was:
const randomInside = (numbers) => {
const array = [numbers]
const newIndex = Math.floor(Math.random() * array.length)
return array[newIndex]
}
but this gives the first item in all occurences. How can I fix this?
You need to collect all arguments into an array if you want to handle it as such. One way of doing so would involve the "rest" parameter ...
:
console.log(randomInside(10,20,25,45)) // desired output is taking one of the numbers, i.e 25
function randomInside(...array){
const newIndex = Math.floor(Math.random() * array.length)
return array[newIndex]
}