<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>随机五个数</title> </head> <body> <h1>第一种:正常数组</h1> <div id="demo"></div> <script type="text/javascript"> var demo = document.getElementById('demo');//获取对象 var arr = ['6666','9999','8888'];//数组 var arrLength = arr.length;//获取数组长度 var sj = Math.random()*arrLength;//随机 var i = Math.floor(sj);//取整 // 赋值 demo.innerHTML=arr[i];//取数组里面的值(下标) </script> <h1>第二种写法:字符串数组</h1> <div id="demo2"></div> <script type="text/javascript"> var demo2 = document.getElementById('demo2'); var arr2 = "一一一,二二二,三三三";//字符串 function num(d){ var fenge = d.split(',');//分割字符串 var arrLength2 = fenge.length; var sj2= Math.random()*arrLength2; var index = Math.floor(sj2); demo2.innerHTML = fenge[index]; } num(arr2) </script> </body> </html>
效果图:
随机1-22:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <p id="demo"></p> <script> // function RandomNumBoth(Min, Max) { // var Range = Max - Min; // var Rand = Math.random(); // var num = Min + Math.round(Rand * Range); // return num; // } // let arr = []; // for (let i = 0; i < 6; i++) { // arr.push(`${parseInt(RandomNumBoth(1, 22))}-${RandomNumBoth(0, 1)}`) // } // let newArr = [...new Set(arr)]; // if (arr.length === newArr.length) { // alert("符合要求了") // } else { // alert("有重复的") // } // console.log(arr) function RandomNumBoth(Min, Max) { var Range = Max - Min; var Rand = Math.random(); var num = Min + Math.round(Rand * Range); return num; } let arr = []; for (let i = 0; i < 6; i++) { let sj = `${parseInt(RandomNumBoth(1, 22))}-${RandomNumBoth(0, 1)}` if (!arr.includes(sj)) { arr.push(sj) } } console.log(arr); </script> </body> </html>