crypto.randomInt([min, ]max[, callback])


  • min <integer> 随机范围的开始(包括)。默认值:0

    ¥min <integer> Start of random range (inclusive). Default: 0.

  • max <integer> 随机范围的结束(不包括)。

    ¥max <integer> End of random range (exclusive).

  • callback <Function> function(err, n) {}

返回随机整数 n,使得 min <= n < max。此实现避免了 模偏差

¥Return a random integer n such that min <= n < max. This implementation avoids modulo bias.

范围 (max - min) 必须小于 248minmax 必须是 安全整数

¥The range (max - min) must be less than 248. min and max must be safe integers.

如果不提供 callback 函数,则同步生成随机整数。

¥If the callback function is not provided, the random integer is generated synchronously.

// Asynchronous
const {
  randomInt,
} = await import('node:crypto');

randomInt(3, (err, n) => {
  if (err) throw err;
  console.log(`Random number chosen from (0, 1, 2): ${n}`);
});// Asynchronous
const {
  randomInt,
} = require('node:crypto');

randomInt(3, (err, n) => {
  if (err) throw err;
  console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
// Synchronous
const {
  randomInt,
} = await import('node:crypto');

const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);// Synchronous
const {
  randomInt,
} = require('node:crypto');

const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
// With `min` argument
const {
  randomInt,
} = await import('node:crypto');

const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);// With `min` argument
const {
  randomInt,
} = require('node:crypto');

const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);