Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of Math.random() in javascript_javascript skills

Detailed explanation of the use of Math.random() in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:04:161559browse

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 continuous integers

Value = Math.floor(Math.random() * total number of possible values ​​first possible value)
Example: Generate random numbers from 1-10

Copy code The code is as follows:

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

Write a function that generates random numbers from startNumber to endNumber

Copy code The code is as follows:

function selectFrom(startNumber, endNumber) {
var choice = endNumber - startNumber 1;
Return Math.floor(Math.random() * choice startNumber)
}
var rand2 = selectFrom(2,8);//Generate random numbers from 2 to 8

2. Obtain a random number from non-adjacent integers

2.1 Obtain a random number from two non-adjacent integers

Example: Randomly generate a number between 2 or 4

Copy code The code is as follows:

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

2.2 Generate a random number from multiple non-adjacent integers

Combined with the function parameter array, you can write a function that generates a random value among multiple non-adjacent integers

Copy code The code is as follows:

function selectFromMess() {
Return arguments[Math.floor(Math.random() * arguments.length)]
}
//Randomly generate a number among 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 every time. You can rewrite the function

Copy code The code is as follows:

function selectFromMessArray(arr) {
Return arr[Math.floor(Math.random() * arr.length)]
}
var arrayTxt=["一","二","三","四","五"];
var randTxt2 = selectFromMessArray(arrayTxt);

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

Copy code The code is as follows:

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

For information about the use of the apply method, please see http://www.jb51.net/article/42705.htm

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn