Math.random()
在javascript 是能够返回1,对吧?这意味着如果我要使用它来获取数组上的随机索引,则以下代码可能会失败:
var arr = [ 1, 2, 3 ],
index = Math.floor(Math.random() * arr.length);
// index could be 3?
alert(arr[index]);
有人可以阐明这一点吗?
最佳答案
您发布的链接会将我带到一个网站,上面写着:
Returns a pseudo-random number in the range [0,1) — that is, between 0 (inclusive) and 1 (exclusive). The random number generator is seeded from the current time, as in Java.
“包含”表示值是范围的一部分,而“不包含”表示值不是范围的一部分。
所以 Math.random()
返回一个从 0 到刚好小于 1 的值。
关于Javascript Math.random() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5580579/