Home >Web Front-end >JS Tutorial >How to randomly select 4 numbers without repeating numbers in js
This article mainly shares with you the method of randomly selecting 4 non-repeating numbers in js, ranging from 0 to 9. I hope it can help you.
html
<input type="button" value="随机生成4位数" onclick="f1()">
script
function f1(){ var arr_4=new Array() function getRandom(min,max) //开始取数 { //随机数 var random = Math.random()*(max-min)+min; //向下取整 random = Math.floor(random); if(arr_4.length < 4) //判断数组长度 { for(i=0;i<=arr_4.length;i++) //遍历数组。 { if(random==arr_4[i]) //比较随机数 { break; } else { if(i==arr_4.length) {arr_4.push(random);break;} } }; getRandom(0,10); } } getRandom(0,10); //随机取0-9 alert(arr_4) }
The above is the detailed content of How to randomly select 4 numbers without repeating numbers in js. For more information, please follow other related articles on the PHP Chinese website!