← 中文资源

简体中文版本

crypto.randomInt 生成有界随机整数

用 crypto.randomInt 生成有界随机整数:上界为开区间、语义明确,避免手写 Math.random 取模引入的分布偏差。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

dice in range: true
1000 draws all in [10, 20): true
collected all six faces: true

实现说明

嵌套的两层循环是 for (let i = 0; i < 1000; i++) 和 while (seen.size < 6) seen.add(randomInt(1, 7));。node:crypto 提供 randomInt——内建表面,不涉及任何包。 dice、inBounds、seen 定义在模块顶层,中间不经过函数作用域。

使用要点

  • node:crypto 是 Node.js 内建模块——随运行时自带,无需安装。
  • 直接运行文件,输出会带上标签,比如 dice in range:、1000 draws all in [10, 20):、collected all six faces:——输出的每一行都能指回产生它的那次调用。

常见问题

它从项目之外导入了什么?

只有 node:crypto,而它是 Node.js 内建的——随运行时提供。

核心语句

const seen = new Set();

代码示例

import { randomInt } from 'node:crypto';

// randomInt(max) draws from [0, max); with two bounds the upper one is excluded
const dice = randomInt(1, 7); // [1, 7) -> 1..6
console.log('dice in range:', dice >= 1 && dice <= 6);

// Range holds across many draws
let inBounds = true;
for (let i = 0; i < 1000; i++) {
  const value = randomInt(10, 20);
  if (value < 10 || value >= 20) inBounds = false;
}
console.log('1000 draws all in [10, 20):', inBounds);

// small ranges collect every face quickly without modulo bias
const seen = new Set();
while (seen.size < 6) seen.add(randomInt(1, 7));
console.log('collected all six faces:', seen.size === 6);