所以,我有 4 次机会(机会 1、机会 2 等)。我想检查一个机会是否等于一,但其他机会都不等于一。我知道我可以检查每一个,但我最终会添加越来越多的机会,并且列表将非常长并且处理起来很烦人。
var chance1 = Math.floor(Math.random() * 10) + 1
var chance2 = Math.floor(Math.random() * 100) + 1
var chance3 = Math.floor(Math.random() * 1000) + 1
var chance4 = Math.floor(Math.random() * 10000) + 1
if (chance1 === 1) {
document.body.innerText = "Red - 1 in 10"
document.body.style.backgroundColor = "red"
}
if (chance2 === 1) {
document.body.innerText = "Orange - 1 in 100"
document.body.style.backgroundColor = "orange"
}
if (chance3 === 1) {
document.body.innerText = "Yellow - 1 in 1,000"
document.body.style.backgroundColor = "yellow"
}
if (chance4 === 1) {
document.body.innerText = "Green - 1 in 10,000"
document.body.style.backgroundColor = "green"
}
再次,我尝试检查每个值,它有效,但我认为最好有一种更有效的方法。
那么您想更新页面以显示最不可能发生的事件吗?
将您的机会以及与该机会对应的颜色存储在数组中。有几种方法可以做到这一点,一种是将它们存储为如下所示的对象
以相反的顺序存储机会,这意味着首先测试最不可能的情况,而不是检查最可能的情况,然后再覆盖。
所以完整的代码可能看起来像这样
你可以把它分解成更小的部分;逻辑函数。
determineChance
~ 抓住机会,更新文档getRandomChance
~ 找一个机会,其中随机值为0formatMessage
~ 根据机会数据格式化消息randInt
~ 生成一个随机整数以下是 1/100 卷的示例: