Javascript - Math.random in a for loop

Just ran into something interesting in Javascript, experimenting with generating a random number in a condition (is this what he called?) Of the for loop.

So, if I wrote the code as follows:

for (var i = 0; i < 20; i++) {
    var count = 0;
    for (var j = 0; j < Math.floor(Math.random() * 20); j++) {
        count++;
    }
    console.log(count);
}

It will return the result as follows:

9
5
8
3
3
2
6
8
4
4
5
6
3
3
5
3
4
5
3
11

But if I were to generate a random number in a variable before the second loop of the loop:

for (var i = 0; i < 20; i++) {
    var count = 0;
    var loopEnd = Math.floor(Math.random() * 20 + 1);
    for (var j = 0; j < loopEnd; j++) {
        count++;
    }
    console.log(count);
}

It will return the result as follows:

11
13
14
2
19
19
17
19
2
18
5
15
18
2
1
19
16
15
13
20

What exactly is going on here? It confused me a little. Is Math.random () inside a for loop creating a new random number after each iteration? Does the code loop, repeat, and test the condition and generate a new random number each time it checks the condition? This is what happens, and why are the numbers in the console less than if I use Math.random () in the variable before the for loop?

+4
2

:

...
for (var j = 0; j < Math.floor(Math.random() * 20); j++) {
    count++;
}
...

j < Math.floor(Math.random() * 20) , Math.random(), .

+3

, , :

, :

, ?

1 20, 10 50% .

, , 2, 3 .., : 95% * 90% * 85% *... * 50 %.

+2

Source: https://habr.com/ru/post/1664085/


All Articles