For details about the use of Math. random () in javascript, javascriptrandom
The Math. random () method returns a random number greater than or equal to 0 and less than 1. For some sites, this method is very practical because it can be used to randomly display some famous quotes and news events.
1. Obtain a random number from a continuous integer
Value = Math. floor (Math. random () * Total number of possible values + first possible value)
For example, a random number ranging from 1 to 10 is generated.
Copy codeThe Code is as follows:
Var rand1 = Math. floor (Math. random () * 10 + 1 );
Compile a function that generates a random number from startNumber to endNumber.
Copy codeThe Code is as follows:
Function selectFrom (startNumber, endNumber ){
Var choice = endNumber-startNumber + 1;
Return Math. floor (Math. random () * choice + startNumber)
}
Var rand2 = selectFrom (); // generates a random number ranging from 2 to 8.
2. Obtain a random number from an unadjacent integer.
2.1 obtain a random number from two unadjacent Integers
For example, a random number of 2 or 4 is generated.
Copy codeThe Code is as follows:
Var rand3 = Math. random () <0.5? 2: 4;
2.2 generate a random number among non-adjacent Integers
In combination with the function parameter array, You can compile a function that generates a random value in an unadjacent integer.
Copy codeThe Code is as follows:
Function selectFromMess (){
Return arguments [Math. floor (Math. random () * arguments. length)]
}
// Generate a random number in values 1, 6, and 8.
Var rand4 = selectFromMess (1, 6, 8 );
// You can also randomly generate text.
Var randomTxt1 = selectFromMess ("Consolation prize", "Second Prize", "First Prize ");
It is troublesome to enter so many parameters each time. You can rewrite the function.
Copy codeThe Code is as follows:
Function selectFromMessArray (arr ){
Return arr [Math. floor (Math. random () * arr. length)]
}
Var arrayTxt = ["1", "2", "3", "4", "5"];
Var randTxt2 = selectFromMessArray (arrayTxt );
Or you can use the apply () method to pass the array parameters without changing the original method.
Copy codeThe Code is as follows:
Var randTxt3 = selectFromMess. apply (null, arrayTxt );
About the use of the apply method can see the http://www.bkjia.com/article/42705.htm
The above is all the content of this article. I hope you will like it.