我在 Stackoverflow 上找到了這段代碼,它在頁面加載時顯示隨機單詞,并在重新加載頁面時顯示一個新單詞。作為 Javascript 的新手,我不知道如何在頁面加載后使其在單詞之間回圈。即每隔一秒從串列中顯示一個新單詞。
該代碼是
var things = ['Rock', 'Paper', 'Scissor'];
var thing = things[Math.floor(Math.random()*things.length)];
alert('The computer chose:' thing);
編輯:我想在頁面上列印結果而不使用警報。
uj5u.com熱心網友回復:
您正在尋找的是setInterval()
const things = ['Rock', 'Paper', 'Scissor'];
setInterval(function() {
const thing = things[Math.floor(Math.random()*things.length)];
console.log('The computer chose : ' thing);
}, 1000)
uj5u.com熱心網友回復:
正確回答您的問題需要了解兩件事。 setInterval和檔案查詢選擇器。為了盡可能以最簡單的方式回答您,我將解決方案分為 HTML 和 JS 代碼。在 HTML 部分中,您可以看到 DOM 元素“p”。它具有稱為“隨機事物”的 ID。在 CSS 中,我們將其稱為 #random-thing。
JavaScript 代碼選擇了這個元素(警告,它可以為空,這就是我們要檢查它是否存在的原因。)。然后我們可以改變元素的屬性innerText。您也可以使用innerHTML更改它,但因為我們只想更改文本內容,所以讓我們使用 innerText 屬性。
html
...
<body>
...
<p id="random-thing"> </p>
...
</body>
...
js
const randomThingDomEl = document.getElementById("random-thing");
const things = ['Rock', 'Paper', 'Scissor'];
const getRandomThing = () => things[Math.floor(Math.random()*things.length)];
setInterval(() => {
if (randomThingDomEl) {
randomThingDomEl.innerText = getRandomThing();
}
}, 1000);
編輯:錯字
uj5u.com熱心網友回復:
因為您只有一小部分要回圈的專案,并且試圖防止連續多次寫入相同的“隨機”專案,所以您必須實施某種“記憶”系統。在這里,我從中復制了陣列和splice單詞,然后在它為空時將其重置。
我也在setTimeout這個例子中使用過。當陣列重置時,您仍然偶爾會連續兩次出現相同的單詞。如果你不想重復的話,你可以在函式中建立檢查,但我認為這違背了“石頭、紙、剪刀”的全部目的——有時你想連續玩 20 次“紙”:)
const arr = ['Rock', 'Paper', 'Scissor'];
// `log` accepts and array of words
function log(arr) {
// Makes a copy of that array
let copy = [...arr];
// Main loop that `setTimeout` calls over and over...
function loop() {
// Get the random number
const rnd = Math.floor(Math.random() * copy.length);
// Get a word by `splicing` it out of the array copy
const word = copy.splice(rnd, 1);
// Log the message
console.log(`The computer chose: ${word}`);
// If there are no words left in the copy, reset it
if (!copy.length) copy = [...arr];
// Call `loop` again
setTimeout(loop, 1000);
}
// Call `loop`
loop();
}
log(arr);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/445814.html
標籤:javascript
上一篇:Redux沒有在反應中更新狀態
