所以我正在用6个随机生成的数字制作JavaScript彩票。有人知道如何防止这些数字相同吗?
谢谢
代码:
'use strict';
function generatenumbers(){
let number = [];
let i;
i=0;
for(i= 0; i <= 5; i++){
number[i] = Math.floor(Math.random()*40);
}
document.getElementById("generated").innerHTML = "";
i = 0;
for(i=0; i<= number.length - 1; i++){
let node = document.createElement("LI");
let txt = document.createTextNode(number[i]);
node.appendChild(txt);
document.getElementById("generated").appendChild(node);
}
}
HTML:
<body>
<div id="container" class="cf">
<header>
<h1>Hipster Powered Lottery</h1>
</header>
<section>
<h2>Play with our wonderful lottery est. 1831</h2>
<a href="#" id="generate" onclick="generatenumbers()">Generate my numbers!</a>
<ul id="generated"></ul>
</section>
<aside>
<h2>Previously generated set</h2>
<ul id="previous"></ul>
</aside>
</div>
</body>
答案 0 :(得分:1)
创建随机数时,仅使用数组中尚未存在的数字:
checkDuplicate(): boolean {
for (let i = 0; i < this.phoneList.length; i++) {
for (let j = 0; j < this.phoneList.length; j++) {
if (i != j) {
if (this.phoneList[i].number === this.phoneList[j].number) {
this.toastrService.error('Phone already in List!');
return true;
}
}
}
}
return false;
}
空的var number = [];
for(i= 0; i <= 5; i++){
var num;
while ( number.includes( num = Math.floor(Math.random()*40) ) );
number[i] = num;
}
console.log(number);
循环反复选择一个数字,直到找到不在while
数组中的数字为止。只有成功完成之后,它才会将该数字添加到数组中。
答案 1 :(得分:0)
random()函数随机生成数字,因此有可能再次出现一个数字。为避免通过 random()函数生成新数字后,您可以检查此数字是否已存在于数组中。仅当它不存在时才将其添加到您的阵列中。下面提供了一个有效的代码段:
function generatenumbers(){
var number = new Array();
var i=0;
while(i<6){
var val = Math.floor(Math.random()*40);
if(number.includes(val) === false){
number.push(val);
i++;
}
}
document.getElementById("generated").innerHTML = "";
i = 0;
for(i=0; i<= number.length - 1; i++){
let node = document.createElement("LI");
let txt = document.createTextNode(number[i]);
node.appendChild(txt);
document.getElementById("generated").appendChild(node);
}
}