Home  >  Article  >  Web Front-end  >  Three ways to implement JavaScript to generate non-repeating random numbers_javascript skills

Three ways to implement JavaScript to generate non-repeating random numbers_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:46:321466browse

In JavaScript, the random numbers generated generally repeat, but sometimes we need non-repeating random numbers. How to achieve this? Next, we will explain three methods to generate non-repeating random numbers and compare them to see which method is more efficient.

Method 1
Idea: First create an array from 1 to 3000, take one number each time, and then remove the number taken out from the array, so that it can never be repeated .

Copy code The code is as follows:



Performance: took 1528 milliseconds.

Method 2
Idea: Improve the slice method of Method 1 to improve efficiency. Or take out a number from the original array, and then assign the value of this position in the original array to null. The next time the number is retrieved, determine whether it is null. If it is null, it will not be retrieved.
Copy code The code is as follows:



Performance: 290 milliseconds.

Method 3
Idea: Break up the original array and then output it one by one. This way, it can be random and never repeated, and it is more efficient.
Copy code The code is as follows:



Performance: takes 229 milliseconds.
Through performance analysis, it is concluded that method three is the best solution.
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