dimanche 18 décembre 2016

Javascript - Math.random in a for loop

Just ran into a something interesting in Javascript while experimenting with generating a random number in the condition (is that what it's called?) of a for loop.

So, if I were to write the code like this:

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 would return a result like this:

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 for 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 would return a result like this:

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

What exactly is happening here? It had me confused for a little while. Is the Math.random() inside the for loop generating a new random number after each iteration? Does the loop run the code, iterate, and check the condition, and generate a new random number each time it is checking the condition? Is this what is happening and is this why the numbers in the console are smaller than if I use Math.random() in a variable before the for loop?




Aucun commentaire:

Enregistrer un commentaire