How can I randomize a variable in JavaScript between 0-4, so that every time the page loads the variable is different but between 0 and 4?
+5
A:
You can use Math.random()
for this. To get a (whole) number between 0 and 4 inclusive, use the following:
var random = Math.floor(Math.random() * 5);
BalusC
2010-07-07 17:58:43
Thank you for the fast reply's! Worked a charm!
David
2010-07-07 18:11:39
+2
A:
// Returns a random integer between min and max
function getRandomInt(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
from mdc (mozilla developer center)
galambalazs
2010-07-07 18:06:56
but fell in love with the typography, so can't delete now. But hey, people vote to BalusC :)
galambalazs
2010-07-07 18:12:04