Implementing random numbers is a common programming task in various programming languages. The following describes how to implement random numbers in JavaScript. The first method is implemented by rewriting the Math. random method, and the second method is changed from a C implementation to realize programming.
Directly run the Code:
<script language="javascript"> var native_random = Math.random;Math.random = function(min, max, exact) {if (arguments.length === 0) {return native_random();} else if (arguments.length === 1) {max = min;min = 0;}var range = min + (native_random()*(max - min));return exact === void(0) ? Math.round(range) : range.toFixed(exact);};document.write(Math.random());document.write('<br />');document.write(Math.random(10));document.write('<br />');document.write(Math.random(3,10));document.write('<br />');document.write(Math.random(2,10,4));</script>
The program running result is as follows:
0.2989420900121331792.2469
How can we not use Math. random to implement random numbers? The following function is changed to a C implementation:
var random = (function(){var high = 1, low = 1 ^ 0x49616E42;var shuffle = function(seed){high = seed;low = seed ^ 0x49616E42;}return function(){ var a = new Date()-0 shuffle(a); high = (high << 16) + (high >> 16); high += low; low += high; return high; }})(); p(random());
<Script type = "text/javascript"> var random = (function () {var high = 1, low = 1 ^ 0x49616E42; var shuffle = function (seed) {high = seed; low = seed ^ 0x49616E42;} return function () {var a = new Date ()-0 shuffle (a); high = (high <16) + (high> 16); high + = low; low + = high; return high ;}) (); alert (random (); </script>