如何在一个js函数中实现两个函数,从而可以在一个html输入中放入两组随机数?我想创建一个函数,它可以通过一次单击生成两组随机数。
从1-50生成5个数字,然后从1-10生成2个数字。一行中的两组数字。
下面的代码不起作用:
function eurojackpot() {
let result = new Set();
while (result.size != 5) {
result.add(Math.floor(Math.random() * 50) + 1);
}
document.getElementById("eurojackpot").innerText = [...result];
let result = new Set();
while (result.size != 2) {
result.add(Math.floor(Math.random() * 10) + 1);
document.getElementById("eurojackpot2").innerText = [...result];
}
}
eurojackpot();<div id="eurojackpot"></div>
<div id="eurojackpot2"></div>
我想要实现的目标:
exp - 2,5,15,23,49 + 1,10
发布于 2018-04-23 18:23:00
当您删除result“的第二个"let”时,代码可以正常工作:
function eurojackpot() {
let result = new Set();
while(result.size != 5){
result.add(Math.floor(Math.random()*50)+1);
}
document.getElementById("eurojackpot").innerText = [...result];
result = new Set();
while(result.size != 2){
result.add(Math.floor(Math.random()*10)+1);
}
document.getElementById("eurojackpot2").innerText = [...result];
}下面是一个重现它的JSFiddle:
发布于 2018-04-23 18:23:42
查看下面的代码片段,在这里您可以指定最小和最大值(您希望随机数出现的范围)作为randomWholeNum函数的第一个和第二个参数,以及随机元素的总数(在您的情况下,第一个参数为5个数字,第二个参数为2个数字)。
点击按钮,它将生成随机数。现在,根据您的需要设置它们的样式。
function randomWholeNum(min, max, total) {
var arr = []
while(arr.length < total){
var randomnumber = Math.floor(Math.random() * (max - min + 1)) + min;
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
return arr;
}
$(".generate").click(function(e){
var rand_no1 = randomWholeNum(1, 50, 5);
var rand_no2 = randomWholeNum(1, 10, 2);
document.getElementById("eurojackpot").innerText = rand_no1;
document.getElementById("eurojackpot2").innerText = rand_no2;
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="eurojackpot"></p>
<p id="eurojackpot2"></p>
<button class="generate">Generate Random Number</button>
发布于 2018-04-23 18:33:04
也许下面的方法对你有用:
const pickRandom = (min,max)=>
Math.floor(Math.random()*max)+min;
const pickFrom = array =>
array[pickRandom(0,array.length-1)];
const pick = (array,amount) => {
const recur = (numbers,array) => {
if(numbers.length>=amount){
return [numbers,array];
}
const picked = pickFrom(array);
return recur(
numbers.concat(picked),
array.filter(item=>item!==picked)
);
}
return recur([],array);
}
document.querySelector("button").addEventListener(
"click",
()=>{
const [jack1] = pick(
Array.from(new Array(50),
(x,index)=>index+1),5
);
const [jack2] = pick(
Array.from(new Array(10),
(x,index)=>index+1),2
);
document.querySelector("#eurojackpot").value=jack1.join(",");
document.querySelector("#eurojackpot2").value=jack2.join(",");
}
);<input type="text" id="eurojackpot">
<input type="text" id="eurojackpot2">
<button>make numbers</button>
https://stackoverflow.com/questions/49978479
复制相似问题