Math.random()
in javascript is able to return 1, right? Which means if I would be to use it to get a random index on my array the following code could fail:
var arr = [ 1, 2, 3 ],
index = Math.floor(Math.random() * arr.length);
// index could be 3?
alert(arr[index]);
Could someone shed some light on this?
The link you posted takes me to a site that says:
"inclusive" means the value is part of the range, whereas "exclusive" means that the value is not part of the range.
So
Math.random()
returns a value from 0 to just-less-than 1.No, it returns from 0 inclusive to 1 exclusive
See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random
Note however the caveat in that page:
For these purposes, though, you should be fine.
between 0 (inclusive) and 1 (exclusive) - cannot be 1
Your code is all right
I am pretty sure the number returned by
is smaller than 1 but equal or greater than zero.