This article mainly introduces the function of a small program for randomly selecting numbers written in JS. It is very good and has reference value. Friends in need can refer to it
I just started learning JavaScript and wrote a random The small program for extracting numbers is attached with all the codes in the body for your reference.
This program can implement the following functions:
1. Enter the maximum number for drawing in the text box
2. Click the button to start drawing numbers and randomly generate 1~max An integer between the values
3. The number that has been extracted cannot be extracted again to ensure the uniqueness of the number
4. Put the number result into the result and display it
5. Store the generated number in exist and display it
The specific code is as follows:
<body> <input type="text" id="txt" placeholder="请在里面输入号码最大值!"> <input type="button" id="btn" value="抽号"> <p> <span>结果:</span> <span id="result"></span> </p> <p> <span>已抽取:</span> <span id="exist"></span> </p> <script type="text/javascript"> var oBtn = document.getElementById("btn"); var oTxt = document.getElementById("txt"); var oRes = document.getElementById("result"); var oExi = document.getElementById("exist"); var arr = []; //存放座号 oBtn.onclick = function() { getSeat(oTxt.value); } function getSeat(maxnum) { for(var i = 0; i < maxnum; i++){ var num = Math.floor(Math.random() * maxnum) + 1; var j; for(j = 0; j < arr.length; j++) { if(num == arr[j]) break; } if(j == arr.length) { arr.push(num); oRes.innerHTML = num; oExi.innerHTML = arr; return; } } } </script> </body>
The running result is as follows:
The above is the detailed content of Detailed example of writing a small program to randomly select numbers using JavaScript. For more information, please follow other related articles on the PHP Chinese website!