Here is the way to get random integers in JavaScript
return Math.floor(Math.random()*8)
the above will return random number from 0 to 7
To get a random number within given range.
return Math.floor(Math.random() * (to - from + 1) + from);
this will return a random number given range from & to
can get a random item from array like below functions:
function getRandomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
}
function getRandomItem(arr){
return arr[getRandomFromTo(0, arr.length - 1)];
}
Comments
Post a Comment