我們的志工尚未將此文章翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!
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. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
Note: 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.
Syntax
Math.random()
Return value
A floating-point, pseudo-random number between 0
(inclusive) and 1 (exclusive).
Examples
Using Math.random()
Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random()
itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound.
// Returns a random number between 0 (inclusive) and 1 (exclusive) function getRandom() { return Math.random(); }
// Returns a random number between min (inclusive) and max (exclusive) function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }
// Returns a random integer between min (included) and max (excluded) // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }
// Returns a random integer between min (included) and max (included) // Using Math.round() will give you a non-uniform distribution! function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. JavaScript 1.0 (UNIX Only) / JavaScript 1.1 (All platforms). |
ECMAScript 5.1 (ECMA-262) The definition of 'Math.random' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Math.random' in that specification. |
Standard | |
ECMAScript 2017 Draft (ECMA-262) The definition of 'Math.random' in that specification. |
Draft |
Browser compatibility
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) |