views:

262

answers:

5

So I am writing this loop, and I have a random number generator in it. How come it only picks one random number for all the iterations of the loop instead of a new random number? here's my code:

for ( i = 0; i < 25; i++ ) {
 var randNum = 0;
 var randNum = Math.floor(Math.random() * 5);
}

this is in the chrome browser. Is there something wrong with this code?

+4  A: 

Is there something wrong with this code?

"It does absolutely nothing" would be the first thing wrong with it.

If this is your "simplified" version of the code, you've "simplified" away important context (such as how you try and use randNum).

Anon.
Agreed. Your code doesn't do much.
Shakedown
+1  A: 

remove the duplicate var in randNum, but on my chrome it works on both cases. Using the mac version. This is probably related to how you are using the randNum, are you using it outside the for somehow? Your code does nothing (like writing the number) atm.

F.Aquino
+2  A: 

Tried it with jQuery output and it works:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;
    </head>
    <body>
      <p></p>
        <script>
        for ( i = 0; i < 25; i++ ) {
             var randNum = 0;
             var randNum = Math.floor(Math.random() * 5);
              $("p").append(" "+randNum);
        }

        </script>
    </body>
</html>

1st time i get output like 4 2 4 1 1 3 3 2 0 1 4 0 3 4 3 1 4 1 1 2 1 1 2 4 2

second: 1 4 1 3 1 3 0 0 2 1 2 1 4 3 2 0 3 3 0 4 4 3 3 4 4

looks fine for me, maybe problem is in diffrent place.

budzor
+3  A: 

If I run that code, I get random numbers:

1 2 2 0 2 1 2 2 1 0 1 0 3 4 2 1 0 3 3 1 1 4 1 2 4

How are you reading the variable? I used this code:

<script type="text/javascript">
for ( i = 0; i < 25; i++ ) {
 var randNum = 0;
 var randNum = Math.floor(Math.random() * 5);
 document.write(randNum + "\n");
}
</script>

We need a bit more context.

EDIT: Lol, 0 answers to 4 in the time it took me to type this :/

elwyn
+2  A: 

You're probably using the randNum variable inside an anonymous function within the loop.

Since the loop always assigns to the same variable, any calls to any of the anonymous functions after the loop finishes will see only the last number.

To fix this, move the body of the loop into a separate function (either named or anonymous).

SLaks