VBScript generating same random number when in loo

2019-01-28 19:20发布

问题:

So I have this function which generates a random string of digits 8 characters long. It works if its called once per page, ie if I refresh it will show a new number.

But I want to generate many of these inside a loop and its returning the same number. How can I solve this?

Function generateCode()

   pChar = "0123456789"

   pCount = Len(pChar) 

   Dim psw
   psw = ""

   Randomize
   For i = 1 To 8 ' password length
      psw = psw & Mid( pChar, 1 + Int(Rnd * pCount), 1 )
   Next

 generateCode= psw
End Function

Now I thought Randomize may be based off the current time, so I took the Randomize line out and called Randomize before the loop that calls generateCode() i- still didn't work!

回答1:

Randomize without any arguments seeds the pseudo-random number generator using the system time. If you call it multiple times very quickly the system time won't have changed so you will reinitialize the PRNG with the same seed each time, giving the same random numbers.

You should only call Randomize only once on your page, not multiple times.