Implementing random numbers is a common programming task in a variety of programming languages, and here's how to implement random numbers in JavaScript. The first method is implemented by overriding the Math.random method, and the second method is changed from a C implementation, which can realize the programming purpose. Tongyu County Zhong agrochemical
Directly on the code:
01 |
<script language= "javascript" > |
02 |
var native_random = Math.random; |
03 |
Math.random = function (min, max, exact) { |
04 |
if (arguments.length === 0) |
06 |
return native_random(); |
08 |
else if (arguments.length === 1) |
13 |
var range = min + (native_random()*(max - min)); |
14 |
return exact === void(0) ? Math.round(range) : range.toFixed(exact); |
16 |
document.write(Math.random()); |
17 |
document.write( ‘<br />‘ ); |
18 |
document.write(Math.random(10)); |
19 |
document.write( ‘<br />‘ ); |
20 |
document.write(Math.random(3,10)); |
21 |
document.write( ‘<br />‘ ); |
22 |
document.write(Math.random(2,10,4)); |
The results of the program run as follows:
How do I implement random numbers without using math.random? The following function is changed from a C implementation:
01 |
var random = ( function (){ |
02 |
var high = 1, low = 1 ^ 0x49616E42; |
03 |
var shuffle = function (seed){ |
05 |
low = seed ^ 0x49616E42; |
11 |
high = (high << 16) + (high >> 16); |
JavaScript random number Generation method