如何使用if(math.random == 50)? [关闭]

问题描述 投票:-6回答:1

所以我试图建立一个选择一个随机数的网站,如果这个数字介于例如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")
        }
    }
}
javascript math random
1个回答
2
投票

而不是使用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();
© www.soinside.com 2019 - 2024. All rights reserved.