javascript - 一旦应用于 var,Math.random 返回相同的数字
问题描述
Math.random
似乎在控制台中工作正常。即使我申请Math.floor
它,也没有问题。但是,一旦我将 a 分配var
给代码。我只是得到相同的号码返回。我写的例子:
数学.随机();<0.2650735060984091
数学.随机();<0.23735521448696772
数学.随机();<0.690841980599159
Math.floor(Math.random() * 10); <8
Math.floor(Math.random() * 10); <7
Math.floor(Math.random() * 10); <1
var x = Math.floor(Math.random() * 10);
<未定义
X; <4
x <4
x <4
x <4
当我分配 any 时,输出始终为 4 var
。
我怎么解决这个问题?
解决方案
您正在做的是存储Math.floor(Math.random() * 10);
in的值x
。不是Math.floor(Math.random() * 10);
每次您使用 x 时都会调用它。这是相同的值。要实现这一点,您需要有一个函数,以便您Math.floor(Math.random() * 10);
每次都可以调用。
function randomFloor() {
return Math.floor(Math.random() * 10)
}
console.log(randomFloor() < 4)
console.log(randomFloor() < 4)
console.log(randomFloor() < 4)
console.log(randomFloor() < 4)
console.log(randomFloor() < 4)
推荐阅读
- python - 使用 numpy 进行批量张量乘法
- java - 如果用户尝试获取带有某些错误的脚本,jshell 会静默完成
- git - Android Studio - git Local Changes 文件列表 - 为什么忽略选项不可点击?
- html - 根据angular2中的第一个div和最后一个div显示或隐藏上一个和下一个按钮
- javascript - 如何将所有计算样式设置为元素上的文字样式?
- javascript - 在单个 Bootstrap Datepicker 中选择一个日期范围
- typo3 - pid 值为 -1 的 tt_content 元素:原因是什么?
- c++ - 如何检查队列是否使用stl排序
- c# - 是否可以在不将 Unity 组件添加到游戏对象的情况下创建它?
- python - 实现 luigi 动态图配置