You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Math.random()生成随机数的疑问:变量与函数调用差异

问题原因拆解

变量赋值是「一次性计算」

当你执行const randomNumber = Math.floor(Math.random()*10)时,右边的表达式会立即执行一次,生成一个随机数后把数值绑定到randomNumber变量上。之后每次访问这个变量,都是直接读取已经存储好的固定值——不管访问多少次,这个值都不会变,就算用let定义,只要不重新赋值,结果也一样。

函数调用是「每次执行都重新计算」

而函数function randomNum () {return Math.floor(Math.random()*10)}的逻辑是:函数定义时内部代码不会执行,只有调用randomNum()的时候,函数体里的代码才会被触发运行,每次调用都会重新执行Math.floor(Math.random()*10)生成新的随机数,所以每次结果都不一样。

直观对比例子

// 变量场景:值固定
const fixedRandom = Math.floor(Math.random() * 10);
console.log(fixedRandom); // 比如输出5
console.log(fixedRandom); // 还是5,不会变

// 函数场景:每次调用生成新值
function getRandom() {
  return Math.floor(Math.random() * 10);
}
console.log(getRandom()); // 可能输出3
console.log(getRandom()); // 可能输出7

内容的提问来源于stack exchange,提问作者Alexander Martinez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:41:02