In javascript Math.random of USES details

  • 2020-05-27 04:24:28
  • OfStack

The Math.random () method returns a random number greater than or equal to 0 and less than 1. For some sites, this method is useful because you can use it to randomly display a list of famous quotes and news events.

1. Get a random number from a series of integers

Value = Math.floor (Math.random () * total number of possible values + the first possible value)
Example: generate a random number from 1 to 10


var rand1 = Math.floor(Math.random() * 10 + 1);

Write functions that generate startNumber to endNumber random Numbers


function selectFrom(startNumber, endNumber) {
    var choice = endNumber - startNumber + 1;
    return Math.floor(Math.random() * choice + startNumber)
}
var rand2 = selectFrom(2,8);// produce 2 to 8 The random number

2. Get a random number from a nonadjacent integer

2.1 get a random number from two non-adjacent integers

Example: randomly generate 1 number in 2 or 4


var rand3 = Math.random() < 0.5 ? 2 : 4;

2.2 generate a random number among non-adjacent integers

Combined with an array of function parameters, a function that generates a random value in nonadjacent integers can be written


function selectFromMess() {
    return arguments[Math.floor(Math.random() * arguments.length)]
}
// Randomly generated 1 , 6 , 8 In the 1 The number of
var rand4 = selectFromMess(1, 6, 8);
// Text can also be generated randomly
var randomTxt1 = selectFromMess(" The consolation prize ", "2 Award, ", "1 Award, ");

It's a little bit of a hassle to enter all these parameters at a time, so you could rewrite the function 1


function selectFromMessArray(arr) {
    return arr[Math.floor(Math.random() * arr.length)]
}
var arrayTxt=["1","2","3","4","5"];
var randTxt2 = selectFromMessArray(arrayTxt);

Or, without changing the old method, you can use apply() to pass the array parameters


var randTxt3 = selectFromMess.apply(null,arrayTxt);

Use can see https about apply method: / / www ofstack. com article / 42705. htm

That's all for this article, I hope you enjoy it.


Related articles: