Math.random 究竟含义为何?

Math.round(Math.random() * 1000)

如题,虽然知道 Math.random 是随机选取 01 之间的一个数,但这样的写法其含义是?
另外 ((Math.random() * 10 + 5).toFixed(1) - 0) 这里的真实含义究竟是?

阅读 6.3k
3 个回答
Math.round(Math.random() * 1000)

表示产生一个随机数并把它放大1000倍再取整,即生成0~1000之间的随机整数。

((Math.random() * 10 + 5).toFixed(1) - 0)

表示产生一个5到15之间,包含一位小数的随机数。
分步解释一下,先产生一个随机数把它乘以10再加上5,即生成5~15的随机数,然后调用toFixed转换成保留1位小数的字符串形式,最后减0是做了隐式转换,把字符串再转换为数字。

Math.random() * 1000 返回一个 0 - 1000 的随机数(包含小数点)
Math.round(Math.random() * 1000) 返回一个 0 -1000的整数

Math.random() * 10 返回一个 0 - 10 的随机数
Math.random() * 10 + 5 返回一个 5 - 15 的随机数
(Math.random() * 10 + 5).toFixed(1) 返回一个保留小数点后一位的 5 - 15 的随机数字符串!
(Math.random() * 10 + 5).toFixed(1) - 0 把字符串转化为Number

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1] that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

Math.random() 产生一个有 N 位小数的伪随机数,范围为 [0, 1)(左闭右开)

n * Math.random() 产生一个 范围为 [0, n) 的随机数,小数为 N - floor(lg(n)) 位

((Math.random() * 10 + 5).toFixed(1) - 0)

其实可以用

Math.floor((Math.random() * 10 + 5) * 10) / 10

替代,其值域为 [5, 15),小数为 1 位

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题