Frederik Lund - 4 months ago 8x

HTML Question

I am pretty new to Javascript, and it seems like i didnt understand the if else statements correctly.

I have a script which will make the visitor go to 1 of 4 websites, but the 2 last sites in my code does not work.

`<script>`

setTimeout(function() {

var r = Math.random();

if(r > 0.49) {

window.location.replace("1.html");

}

else if(r < 0.48) {

window.location.replace("2.html");

}

if (r == 0.48){

window.location.replace("maybe.html");

}

else if (r == 0.49){

window.location.replace("4.html");

}

}, 1);

</script>

Is how my code looks like right now. How would it need to look to make it work?

Answer

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");
}
```

Source (Stackoverflow)

Comments