Math.random()
Normally we use Math.random()
to generate pseudo-random numbers, which can be easily used in most cases. for example
Generate mixed random characters
Math.random().toString(36).substr(2);
Generate a random number in the specified range
const randomNumber = (min, max) => Math.floor(Math.random() * (max - min) + min);
But if it involves a slightly more rigorous scenario, the Math.random()
is not even enough. At this time, you can use the more secure random number generation interface Crypto.getRandomValues()
Crypto.getRandomValues()
Crypto
looks relatively unfamiliar, this is the browser provides a basic cryptographic operation interface.
Among them, a random number generation method getRandomValues
. Math.random()
is not evenly distributed. Although there will be no conflicts in most cases, it does have hidden dangers. And getRandomValues
compatibility is still good.
To generate a random number, you must first provide a TypedArray
object, and the generated random number will rewrite the object in it.
window.crypto.getRandomValues(new Uint32Array(5))
Crypto.getRandomValues()
is still relatively primitive to use directly, and you need to process the data again by yourself. There are also generated codes that can be used directly on the Internet:
Generating [0, 1)
random number between (and Math.random()
same)
const cryptoRand = () => {
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
return ( randomBuffer[0] / (0xffffffff + 1) ); // 0xFFFFFFFF = uint32.MaxValue (+1 because Math.random is inclusive of 0, but not 1)
}
Generate random number in specified range
const randomNumber = (min, max) => {
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
const number = randomBuffer[0] / (0xffffffff + 1);
return Math.floor(number * (max - min) + min);
}
Generate ID
const generateId = (len) => {
const typeArray = new Uint8Array((len || 40) / 2)
window.crypto.getRandomValues(typeArray)
return Array.from(typeArray, dec=>dec.toString(16).padStart(2, "0")).join('')
}
Or
const uuidv4 = () => ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
It should be noted that there is crypto.getRandomValues
, but a pseudo-random number generator with sufficient entropy is used. If an encryption scenario is required, the user needs to provide a seed of sufficient entropy source.
Or use the ready-made random number generation library nanoid
.
Nano ID
Nano ID is a small, secure, URL-friendly, unique JavaScript string ID generator. Support browsers, Node.js, React Native, and provide various other language versions.
Install
npm install --save nanoid
Generate random numbers safely:
Synchronize
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
asynchronous
import { nanoid } from 'nanoid/async'
await nanoid()
If you are more concerned about performance, you can reduce security and use non-secure random number generators
import { nanoid } from 'nanoid/non-secure'
const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
Of course, you can also customize random characters and sizes, and you can check the document for specific methods.
Relevant information
MDN - Crypto.getRandomValues()
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。