Home > Web Front-end > JS Tutorial > body text

How to get random numbers without repetition in jquery

藏色散人
Release: 2020-11-30 16:46:53
Original
2821 people have browsed it

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;
            }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!