我試圖獲取陣列的不同值并在每次用戶單擊按鈕時列印它們。
`
<p id="demo" style="display: none"></p>
<button
id="myB"
onclick="loto()"
style="background: #26a775; font-family: Monospace; border-radius: 15%"
>
And The Numbers Are
</button>
<script>
const lottery = [];
function loto() {
for (let i = 0; lottery.length < 7; i ) {
let index = Math.floor(1 Math.random() * 32);
if (!lottery.includes(index)) {
//if lottery not includes this specific index >>
lottery.push(index);
} //push the index
demo.style.display = "block";
demo.style.color = "#ff7300";
demo.innerHTML = lottery;
}
}
console.log(lottery);
</script>
`
uj5u.com熱心網友回復:
在函式內部宣告彩票,以便重繪 。您將一直回圈到 lottery.length < 7。當您執行此操作并在函式范圍之外宣告 lottery[] 并向其推送 7 個值時,lottery[] 將永遠不會觸發 for 回圈。還考慮將 HTML 和 console.log(lottery) 移到回圈之外,以便它們只更新一次,而不是每次迭代
<script>
function loto() {
//now inside of function. each time loto() is called, a new array will be there.
const lottery = [];
for (let i = 0; lottery.length < 7; i ) {
let index = Math.floor(1 Math.random() * 32);
if (!lottery.includes(index)) {
//if lottery not includes this specific index >>
lottery.push(index);
} //push the index
}
//now outside of loop//
demo.style.display = "block";
demo.style.color = "#ff7300";
demo.innerHTML = lottery;
console.log(lottery);
}
</script>
uj5u.com熱心網友回復:
<p id="demo" style="display: none"></p>
<button
id="myB"
onclick="loto()"
style="background: #26a775; font-family: Monospace; border-radius: 15%"
>
And The Numbers Are
</button>
<script>
const demo = document.querySelector("#demo");
let lottery = [];
function loto() {
for (let i = 0; lottery.length < 7; i ) {
let index = Math.floor(1 Math.random() * 32);
if (!lottery.includes(index)) {
//if lottery not includes this specific index >>
lottery.push(index);
} //push the index
}
demo.style.display = "block";
demo.style.color = "#ff7300";
demo.innerHTML = lottery.join(" ");
// console.log(lottery); this will print the new numbers in the array
lottery = [];
}
</script>
uj5u.com熱心網友回復:
lottery每次loto呼叫都需要重置。所以基本上只是lottery = [] 在宣告后做loto:
<p id="demo" style="display: none"></p>
<button
id="myB"
onclick="loto()"
style="background: #26a775; font-family: Monospace; border-radius: 15%"
>
And The Numbers Are
</button>
<script>
const demo = document.querySelector("#demo");
function loto() {
const lottery = [];
for (let i = 0; lottery.length < 7; i ) {
let index = Math.floor(1 Math.random() * 32);
if (!lottery.includes(index)) {
//if lottery not includes this specific index >>
lottery.push(index);
} //push the index
demo.style.display = "block";
demo.style.color = "#ff7300";
demo.innerHTML = lottery.join(" ");
}
console.log(lottery);
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426126.html
標籤:javascript html css
