[英]Why does this Increment not work?
我在使用此代码时遇到了一些问题。 我的问题是,使用下面的代码,它没有加上带有'incr'的检测比率文本。 它只输入incr,但不加。
这是我的代码。
(function loop() {
var rand = Math.round(Math.random() * (3000 - 500)) + 500;
var incr=Math.floor(Math.random()*6);
setTimeout(function() {
document.getElementById('detection-ratio').innerText = '0 / '+ ++incr;
loop();
}, rand);
}());
默认情况下,“检测比率”文本如下所示:
0 / 0
然后,假设“ incr”生成数字“ 3”,然后应该将最后一个0加3,所以它看起来像这样:
0 / 3
然后,假设它将生成一个新的“ incr”,例如“ 5”。 然后看起来像这样:
0 / 8
--->但是现在,它还没有这样做。 它只是将“ incr”写入“检测比率”而不增加它。
我假设您正在尝试将文本附加到检测比例,如果需要的话
document.getElementById('detection-ratio').innerText += '0 / '+ incr;
变量前的++是预递增运算符,因为您正在生成随机数,所以我假设这实际上不是您想要的。
希望这段代码可以帮助您获得预期的输出,如果有什么问题请让我知道。 一旦达到> 26,也停止迭代
var incr = 0;
(function loop() {
var rand = Math.round(Math.random() * (3000 - 500)) + 500;
incr += Math.floor(Math.random()*6);
setTimeout(function() {
console.log('0 / '+ incr);
loop();
}, rand);
}());
感谢您的解释和耐心等待。
由于无论如何都是递归地调用循环,因此您可能需要考虑一种更实用的方法:
(function loop(startctr) {
var rand = Math.round(Math.random() * (3000 - 500)) + 500;
nextctr = startctr + Math.floor(Math.random()*6);
setTimeout(function() {
console.log('0 / '+ nextctr);
loop(nextctr);
}, rand);
}(0));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.