简体   繁体   English

Javascript Math.random()

[英]Javascript Math.random()

Math.random() in javascript is able to return 1, right? Math.random()在JavaScript 能够返回1,对不对? 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? 有人可以对此有所了解吗?

No, it returns from 0 inclusive to 1 exclusive 不,它从0到包括 独家 1返回

See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random 请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random

Note however the caveat in that page: 但请注意该页面中的警告:

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, these ranges, excluding the one for Math.random() itself, aren't exact, and depending on the bounds it's possible in extremely rare cases (on the order of 1 in 2 62 ) to calculate the usually-excluded upper bound. 请注意,由于JavaScript中的数字是具有舍入到最近偶数行为的IEEE 754浮点数,因此这些范围(不包括Math.random()本身的范围)并不精确,并且取决于极限,它可能极其可能罕见的情况下,计算(1 2 62的数量级上)的通常排除上限。

For these purposes, though, you should be fine. 但是,出于这些目的,你应该没问题。

The link you posted takes me to a site that says: 您发布的链接将我带到一个网站,上面写着:

Returns a pseudo-random number in the range [0,1) — that is, between 0 (inclusive) and 1 (exclusive). 返回范围[0,1)中的伪随机数 - 即0(包括)和1(不包括)之间的伪随机数。 The random number generator is seeded from the current time, as in Java. 随机数生成器从当前时间播种,如在Java中。

"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. 所以Math.random()返回一个从0到小于1的值。

I am pretty sure the number returned by 我很确定返回的号码

Math.random() 的Math.random()

is smaller than 1 but equal or greater than zero. 小于1但等于或大于零。

between 0 (inclusive) and 1 ( exclusive ) - cannot be 1 介于0(含)和1( 不包括 ) -不能是1

Your code is all right 你的代码没问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM