You can replace your entire code block with these 2 lines, and they will do what you want:
var r = Math.floor(Math.random() * 4) + 1;
window.location.replace(r+".html");
Explanation:
Your code is actually working. The problem is that the number returned by Math.random()
is a random number between 0 and 1 (it might be 0.5544718541204929 ), and will almost NEVER be exactly 0.48 or 0.49, but will almost always be between those two numbers.
A better solution would be:
var r = Math.floor(Math.random() * 4) + 1;
and then test if number is 1, 2, 3 or 4.
Example:
jsFiddle Demo //jsFiddle temporarily not saving fiddles
var r = Math.floor(Math.random() * 4) + 1;
if(r ==1) {
alert("1.html");
}else if(r==2){
alert("2.html");
}else if(r==3){
alert("3.html");
}else{
alert("4.html");
}
BUT there is no need for the entire IF block. Just do this:
var r = Math.floor(Math.random() * 4) + 1;
window.location.replace(r+".html");
//alert( r + ".html" );
In response to the this question, submitted as a comment: I want it to be page 1 and page 2 has is almost 50/50, and the last 2 is pretty rare
This would give odds of 1% for cases 3 and 4.
var r = Math.floor(Math.random() * 100) + 1; //return number between 1 and 100
if(r <=48) {
alert("1.html");
}else if(r<=98){
alert("2.html");
}else if(r==99){
alert("3.html");
}else{ //r==100
alert("4.html");
}
If you desire slightly larger odds:
if(r <=40) { //40% chance
alert("1.html");
}else if(r<=80){ //40% chance
alert("2.html");
}else if(r<=90){ //10% chance
alert("3.html");
}else{ //r is between 91 and 100, 10% chance
alert("4.html");
}