所以,我有 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"
}
我再次尝试检查每个值,它有效,但我认为最好有一种更有效的方法。
您想更新页面以显示发生的最不可能的事件吗?
将您的机会以及与该机会对应的颜色存储在数组中。有几种方法可以做到这一点,一种是将它们存储为如下所示的对象
{
chance: 1000,
color: 'green',
}
以“相反的顺序”存储机会,意味着首先测试最不可能的情况,而不是检查“最有可能”的情况,然后再覆盖。 所以完整的代码可能看起来像这样
const chances = [
{ chance: 10000, color: 'green' },
{ chance: 1000, color: 'yellow' },
{ chance: 100, color: 'orange' },
{ chance: 10, color: 'red' },
];
function determineChance() {
for (let {chance, color} of chances) {
const roll = Math.floor(Math.random() * chance) + 1;
if (roll === 1) {
const capColor = color[0].toUpperCase() + color.slice(1);
document.body.innerText = `${capColor} - 1 in ${chance}`;
document.body.style.backgroundColor = color;
return;
}
}
// If here, no hits
document.body.innerText = 'No hits';
}
determineChance();