當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js crypto.randomInt([min, ]max[, callback])用法及代碼示例

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

曆史
版本變化
v18.0.0

將無效回調傳遞給 callback 參數現在會拋出 ERR_INVALID_ARG_TYPE 而不是 ERR_INVALID_CALLBACK

v14.10.0、v12.19.0

添加於:v14.10.0、v12.19.0


參數
  • min <integer> 隨機範圍的開始(包括)。 默認: 0
  • max <integer> 隨機範圍結束(不包括)。
  • callback <Function> function(err, n) {}

返回一個隨機整數 n 使得 min <= n < max 。此實現避免了 modulo bias

範圍 (max - min) 必須小於 248。minmax 必須是 safe integers

如果沒有提供callback函數,則同步生成隨機整數。

// 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}`);

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 crypto.randomInt([min, ]max[, callback])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。