使用Javascript的Math.random() [英] Javascript Math.random()

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

问题描述

的Math.random() 在JavaScript中的能够返回1,对不对?这意味着,如果我会用它来得到我的阵列上的随机指标如下code可能会失败:

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:

返回的一伪随机数
  范围[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" 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天全站免登陆