数学随机加减计数器限制在一系列数字之间
Math random add subtract counter limited between a range of numbers
你能帮我看看如何将以下值限制在最小和最大范围内,例如 3 - 10
<div id="number">3</div>
setInterval(function(){
random = (Math.floor((Math.random()*1)+1));
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
random = random * plusOrMinus;
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 1000);
参见 Mozilla 文档:
Getting a random integer between two values This example returns a random integer between the specified values. The value is no lower
than min (or the next integer greater than min if min isn't an
integer), and is less than (but not equal to) max.
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
由 Mozilla 贡献者提供,根据 CC-BY-SA 2.5 获得许可。
你能帮我看看如何将以下值限制在最小和最大范围内,例如 3 - 10
<div id="number">3</div>
setInterval(function(){
random = (Math.floor((Math.random()*1)+1));
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
random = random * plusOrMinus;
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 1000);
参见 Mozilla 文档:
Getting a random integer between two values This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max.
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
由 Mozilla 贡献者提供,根据 CC-BY-SA 2.5 获得许可。