javascript - 如何使用 if(math.random == 50)?
问题描述
所以我正在尝试制作一个选择随机数的网站,如果该数字在例如 50-60 之间,它将会做一些事情
这是一些代码:
var opengg;
window.onload = function() {
opengg = function() {
console.log(Math.floor(Math.random() * 100));
if (Math.floor(Math.random() * 100) == 50) {
console.log("test")
}
}
}
解决方案
不要使用Math.floor(Math.random() * 100)
两次,而是只使用一次,因为每次它都会生成一个新数字并将其分配给一个变量并检查它是否在 50 和 60 之间。Math.floor(Math.random() * 100)
内部console.log();
&的结果if ()
不太可能相等。因此,即使您看到数字日志在范围内,但在if
的条件语句中很少会是相同的数字
let opengg = function() {
let num = Math.floor(Math.random() * 100);
console.log(num)
if (num >= 50 && num <= 60) {
console.log("test")
}
}
opengg();
推荐阅读
- java - Nativescript扩展java类生成未知构造函数
- mysql - 添加计算字段的结果
- python - 如何从我美丽的汤结果中删除标签(如:地址 = [a,b,c,d,r......])
- python - 访问字典中的熊猫面具
- ios - ScrollView 使用 SwiftUI 获取/设置滚动位置
- python - 从 MATLAB 到 Python 的错误状态卡尔曼滤波器
- javascript - 如何从 javascript 变量中获取值,通过按钮用作 php 输入变量,没有或没有提交按钮?
- excel - 数据导入操作在被快捷方式触发时停止,但在调试模式下工作
- arrays - 如何从bash函数返回数组
- java - 在java中解析json字符串:位置1的意外字符(P)