MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

 

Math.random() 函数返回一个浮点,  伪随机数在范围[0,1),然后您可以缩放到所需的范围。

实现选择初始种子进行随机数生成算法;它不能被用户选择或重置。

[0,1) === [即从0(包含0)到...1但不包括1(排除1)。

[0,1) === 左开右闭区间

Math.random() does not provide cryptographically secure random numbers.

Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

语法

Math.random()

参数

示例

例子: 使用 Math.random

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.

// 返回一个大于等于0,小于1的伪随机数
function getRandom() {
  return Math.random();
}
// 返回一个介于min和max之间的随机数
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
// 返回一个介于min和max之间的整型随机数
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

规范

规范版本 规范状态 注解
ECMAScript 1st Edition. JavaScript 1.0 (UNIX Only) / JavaScript 1.1 (All platform) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
Math.random
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
Math.random
Standard  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

 

文档标签和贡献者

 此页面的贡献者: xgqfrms-GitHub, AlexChao, teoli, ndon
 最后编辑者: xgqfrms-GitHub,