Javascript Math.random() [英] Javascript Math.random()

查看:33
本文介绍了Javascript Math.random()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Math.random() 在 javascript 能够返回 1,对吗?这意味着如果我要使用它来获取数组上的随机索引,以下代码可能会失败:

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]);

有人可以解释一下吗?

推荐答案

您发布的链接将我带到一个网站,该网站说:

The link you posted takes me to a site that says:

返回一个伪随机数范围 [0,1) — 即在 0 之间(含)和 1(不含).这随机数生成器来自当前时间,就像在 Java 中一样.

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.

inclusive"表示该值是范围的一部分,而exclusive"表示该值不是范围的一部分.

"inclusive" means the value is part of the range, whereas "exclusive" means that the value is not part of the range.

所以 Math.random() 返回一个从 0 到小于 1 的值.

So Math.random() returns a value from 0 to just-less-than 1.

这篇关于Javascript Math.random()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆