[英]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.