简体   繁体   English

为什么此增量不起作用?

[英]Why does this Increment not work?

I'm having some problems with this code. 我在使用此代码时遇到了一些问题。 My problem is that with the code below, it doesn't plus the detection-ratio text with the 'incr'. 我的问题是,使用下面的代码,它没有加上带有'incr'的检测比率文本。 It just enters the incr, but doesn't plus. 它只输入incr,但不加。


This is my code. 这是我的代码。

(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);
}());

The 'detection-ratio' text looks like this as default: 默认情况下,“检测比率”文本如下所示:

0 / 0

Then, lets say 'incr' generates the number '3', then it should increase the last 0 with 3, so it would look like this: 然后,假设“ incr”生成数字“ 3”,然后应该将最后一个0加3,所以它看起来像这样:

0 / 3

Then, lets say it's going to generate a new 'incr', lets say '5'. 然后,假设它将生成一个新的“ incr”,例如“ 5”。 Then it would look like this: 然后看起来像这样:

0 / 8

---> But right now, it doesn't do that. --->但是现在,它还没有这样做。 It just writes the 'incr' into the 'detection-ratio' without increasing it. 它只是将“ incr”写入“检测比率”而不增加它。

I am assuming you are trying to append text to detection-ratio if so you need to 我假设您正在尝试将文本附加到检测比例,如果需要的话

document.getElementById('detection-ratio').innerText += '0 / '+ incr;

++ before a variable is a pre-increment operator, since you are generating random numbers i am assuming that is not actually what you want. 变量前的++是预递增运算符,因为您正在生成随机数,所以我假设这实际上不是您想要的。

Hope this code would help you to get the expected output, let me know if something breaks. 希望这段代码可以帮助您获得预期的输出,如果有什么问题请让我知道。 Also stop iteration once it reaches > 26 一旦达到> 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);
    }());

Thanks for the explanation and patience. 感谢您的解释和耐心等待。

Since you're calling the loop recursively anyway, you may want to consider a more functional approach: 由于无论如何都是递归地调用循环,因此您可能需要考虑一种更实用的方法:

(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM