Home > Article > Web Front-end > JavaScript randomly selects 10 non-repeating numbers between 0-100_javascript skills
Currently, I have only learned two simple methods to help you randomly select 10 non-repeating numbers between 0-100. The details are as follows
The first method Use the feature that the array length can be rewritten
Idea: You can use a for loop to loop out the numbers from 0 to 100 and put them in an array, and then use sort( ) randomly scrambled, and then by rewriting the length of this array to 10, 10 different numbers were obtained.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> var arr=[]; for(var i=0;i<100;i++){//一个从0到100的数组 arr.push(i); } arr.sort(function(){//随机打乱这个数组 return Math.random()-0.5; }) arr.length=10;//改写长度 console.log(arr);//控制台会输出10个不同的数 </script> </head> <body> </body> </html>
The second one takes advantage of the unique key value of the json object.
Idea: first define an empty array to save the array and an empty json object,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> //json对象,key值是唯一的,key值可以为数字 var arr=[]; var json={}; while(arr.length<10){ var k=Math.round(Math.random()*100); if(!json[k]){ json[k]=true; arr.push(k); } } console.log(arr) </script> </head> <body> </body> </html>
The above is the content of JavaScript techniques for randomly selecting 10 non-repeating numbers between 0-100. For more related content, please pay attention to the PHP Chinese website ( www.php.cn)!