A random number generator statement in a loop is giving me the same number every time. Javascript
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?开发者_JS百科
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
).
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.
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).
Tried it with jQuery output and it works:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</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.
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.
精彩评论