The Math.random () method returns a random number that is greater than or equal to 0 less than 1. For some sites, this approach is useful because it can be used to randomly display celebrity quotes and news events.
1. Get a random number in a continuous integer
Value = Math.floor (Math.random () * Total number of possible values + first possible value)
Example: A random number that produces 1-10
Copy Code code as follows:
var rand1 = Math.floor (Math.random () * 10 + 1);
Write a function that produces startnumber to endnumber random numbers
Copy Code code as follows:
function Selectfrom (Startnumber, Endnumber) {
var choice = Endnumber-startnumber + 1;
Return Math.floor (Math.random () * Choice + startnumber)
}
var rand2 = Selectfrom (2,8);//generating random numbers from 2 to 8
2. Get a random number in a nonadjacent integer
2.1 Obtains a random number in the nonadjacent two integers
Example: randomly generating a number in 2 or 4
Copy Code code as follows:
var rand3 = Math.random () < 0.5? 2:4;
2.2 Generating a random number in nonadjacent multiple integers
A function that combines a function parameter array to produce a random value in a nonadjacent number of integers
Copy Code code as follows:
function selectfrommess () {
Return Arguments[math.floor (Math.random () * arguments.length)]
}
Randomly generate a number in 1, 6, 8
var rand4 = selectfrommess (1, 6, 8);
Text can also be generated randomly
var randomTxt1 = selectfrommess ("Consolation Prize", "Second Prize", "First Prize");
Each time you want to enter so many parameters more trouble, you can rewrite the function
Copy Code code as follows:
function Selectfrommessarray (arr) {
Return Arr[math.floor (Math.random () * arr.length)]
}
var arraytxt=["One", "two", "three", "four", "five"];
var randTxt2 = Selectfrommessarray (arraytxt);
Or do not change the original method, you can use the Apply () method to pass the array parameters
Copy Code code as follows:
var randTxt3 = selectfrommess.apply (null,arraytxt);
The use of the Apply method can be seen http://www.jb51.net/article/42705.htm
The above mentioned is the entire content of this article, I hope you can enjoy.