Math.random
returns a number between 0 and 1. See the documentation on MDN.
Also, see this question about generating a random number in a specific range.
So, you have two problems: one, you're not generating a random number in the range you think you are, and two, you're not using the random number you generated.
I made this fiddle that does something similar to what you described.
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateRandomWithExclusion(exclude, min, max) {
var num = getRandomInt(min, max);
while (num === exclude) {
num = geRandomInt(min, max);
}
return num;
}
generateRandomWithExclusion(2, 0, 10) // returns an integer between 0 and 10 that is not 2
You pass the number you want to exclude and a range of min
and max
, and get a random integer in that range that isn't the number you want excluded.