淘先锋技术网

首页 1 2 3 4 5 6 7

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?

解决方案

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