Join MDN and developers like you at Mozilla's View Source conference, 12-14 September in Berlin, Germany. Learn more at https://viewsourceconf.org

Math.random()

概述

Math.random() 函数返回 [0-1) 的浮点值伪随机数(大于等于0,小于1)。

此函数的随机数生成器和java一样以当前时间为随机数种子。

语法

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)

 

文档标签和贡献者

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