Home>Article>Web Front-end> How to get random numbers without repetition in jquery

How to get random numbers without repetition in jquery

藏色散人
藏色散人 Original
2020-11-23 10:56:52 2748browse

Jquery method to obtain non-repeating random numbers: first define an array to store random numbers; then limit the range by lengths; then use the "parseInt(Math.random() * arrLen);" method to generate within the range Data; finally remove duplicate values.

How to get random numbers without repetition in jquery

Recommended: "jquery video tutorial"

The operating environment of this tutorial: windows7 system, jquery3.2.1 version, This method works for all brands of computers.

Jquery method of obtaining non-repeating random numbers:

JQ obtaining non-repeating random numbers - custom range

The code is as follows:

//获取不重复随机数 function getRandom(lengths) { var arr = [];//存放随机数的数组 var arrLen = lengths;//用来限制范围 for(var i=0; i<4; i++){ var radomNum = parseInt(Math.random() * arrLen);//生成范围内的数据数 if(arr.indexOf(radomNum) == -1){ //indexOf返回值为-1表示数组中没有和新随机数重复的值 arr.push(radomNum); }else{ //有重复值i--,不添加重复的值到数组中,并再循环一次 i--; } } console.log(arr); return arr; }

The above is the detailed content of How to get random numbers without repetition in jquery. For more information, please follow other related articles on the PHP Chinese website!

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