我不明白为什么这个while
循环是无限的:
window.prevRandomNumber = -1;
function getRandomNumber(limit) {
if (!limit)
limit = 9;
var actualRandomNumber = Math.floor((Math.random() * limit) + 1);
while (window.prevRandomNumber == actualRandomNumber) {
actualRandomNumber = Math.floor((Math.random() * limit) + 1)
}
window.prevRandomNumber = actualRandomNumber;
return actualRandomNumber;
}
对此的 QUnit 测试:
test("getRandomNumber() should never return the same number once and again", function () {
//http://www.askageek.com/2006/01/31/javascript-random-function-that-does-not-return-two-consecutive-identical-results/
var prevNumber, actualNumber, assertResult;
for (var i = 0; i <= 200; i++) {
actualNumber = getRandomNumber();
assertResult = prevNumber != actualNumber;
equal(assertResult, true);
if (!assertResult)
break;
prevNumber = actualNumber;
}
});
解决方案:
抱歉,错误出现在另一个测试中,就像@Jon 回答的描述一样,当 anyNumber 等于 1 时,会发生无限循环:
test("getRandomNumber(anyNumber) should return a number between 1..anyNumber", function () {
var anyNumber, result;
for (var i = 0; i <= 100; i++) {
anyNumber = Math.floor((Math.random() * 9) + 1);
result = getRandomNumber(anyNumber);
equal((0 < result && result < (anyNumber + 1)), true);
}
});