最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Javascript Math.random() - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question asked Apr 7, 2011 at 11:52 KevinKevin 5,6943 gold badges29 silver badges42 bronze badges 8
  • 5 Did you even read the documentation you linked to? The answer is right there on the first sentence. – R. Martinho Fernandes Commented Apr 7, 2011 at 11:54
  • I did, but I wasn't sure what exclusive meant. – Kevin Commented Apr 7, 2011 at 11:56
  • 1 @Kevin: Then this question is off-topic and would have been better served on english.stackoverflow., posed purely as a language question. – Lightness Races in Orbit Commented Apr 7, 2011 at 11:58
  • wanna clear it in the separate topic? :) No, it can't be. – Emmerman Commented Apr 7, 2011 at 11:58
  • @Emmerman: Stack Overflow is not a forum; it has questions and answers, not "topics". – Lightness Races in Orbit Commented Apr 7, 2011 at 11:58
 |  Show 3 more ments

4 Answers 4

Reset to default 8

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). 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.

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/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 262) to calculate the usually-excluded upper bound.

For these purposes, though, you should be fine.

I am pretty sure the number returned by

Math.random()

is smaller than 1 but equal or greater than zero.

between 0 (inclusive) and 1 (exclusive) - cannot be 1

Your code is all right

发布评论

评论列表(0)

  1. 暂无评论