如何检查2次随机数的尝试是否相同?

时间:2018-03-09 01:26:38

标签: javascript html

我试图找出一个if语句,它允许我检查当前(Math.floor(Math.random()* 5)给我的值与之前的尝试相同吗?我知道我可以得到它将它打印出去但有没有办法让系统检查?

2 个答案:

答案 0 :(得分:0)

您需要将之前的值和可选的当前值存储到变量并进行比较。 e.g:

假设:

function randomInteger(limit) {
    return Math.floor(Math.random() * limit);
}

您可以将两者存储到变量并进行比较:

var previousValue = randomInteger(5);
var currentValue = randomInteger(5);
if (currentValue === previousValue) {
    /* your conditional code here */
}

或者您可以跳过将当前值存储到变量并直接比较新值:

if (randomInteger(5) === previousValue) {
    /* your conditional code here */
}

答案 1 :(得分:-1)

只需检查此布尔值: Math.floor(Math.random()*5) === Math.floor(Math.random()*5)