FakeBrain - 1 year ago 60

Javascript Question

I have a function that is supposed to be used to randomly redirect to another page:

`function () {`

var rand_exp = ['v', 'a'];

var pick_exp = function(expType) {

return expType[Math.floor(Math.random()*expType.length)];

}

if (pick_exp(rand_exp) === 'v') {

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

} else if (pick_exp(rand_exp) === 'a') {

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

}

}

I've tested this several times and 1 of 3 things seem to happen, it will either redirect to one of the two clauses in the if and else if statements or it will redirect to the page the above javascript is imbedded in, in which case I just have a blank screen, is this to be expected ?

Answer Source

Are there more than two possible outcomes for this function ?

No, your universal set is limited to `['v', 'a']`

.

And this line

```
return expType[Math.floor(Math.random()*expType.length)];
```

will only return 'v' or 'a', since `expType.length`

is **2**

Math.random returns a fraction value between 0 and 1 (less than 1).

When you multiply that value with 2 (`expType.length`

), output will always be less than 2, on top of which if you do `Math.floor`

, then output will be either 0 or 1.