我在Stackoverflow上找到了这段代码,它在页面加载中显示随机单词,并在重新加载页面时显示一个新的单词。作为Javascript的新手,我不知道如何使它在页面加载后的单词之间循环。这是在每一秒之后从列表中显示一个新单词。
守则是
var things = ['Rock', 'Paper', 'Scissor'];
var thing = things[Math.floor(Math.random()*things.length)];
alert('The computer chose:' + thing);
编辑:我想在页面上发布结果,而不使用警告。
发布于 2022-03-21 13:19:33
因为您只有一小部分要循环的项,并且试图阻止连续多次写入相同的“随机”项,所以您必须实现某种“记忆”系统。在这里,我从数组中复制了一个数组和splice
单词,然后在它为空时重新设置它。
在本例中,我还使用了setTimeout
。(个人偏好)在数组重置时,偶尔也会有相同的单词连续出现两次。如果你不想重复的话,你可以在函数中建立这个检查,但我认为这违背了“石头、纸、剪刀”的全部目的--有时你想连续播放“纸”20次:)
const arr = ['Rock', 'Paper', 'Scissor'];
const el = document.querySelector('#demo');
// `log` accepts and array of words, and an element
function log(arr, el) {
// 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);
// Updated the element text content
el.textContent = `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, el);
<div id="demo"></div>
发布于 2022-03-21 12:52:37
你要找的是setInterval()
const things = ['Rock', 'Paper', 'Scissor'];
setInterval(function() {
const thing = things[Math.floor(Math.random()*things.length)];
console.log('The computer chose : ' + thing);
}, 1000)
发布于 2022-03-21 13:00:03
正确回答你的问题需要了解两件事。setInterval和文档查询选择器。为了尽可能简单地回答您,我已经将HTML和JS代码的解决方案分开了。在HTML部分,您可以看到DOM元素"p“。它有一个名叫“随机物”的ID。在CSS中,我们把它称为#随机事物。
JavaScript代码选择此元素(警告,它可以为null,这就是为什么我们要检查它是否存在.)。然后,我们可以更改元素的属性innerText。您也可以使用innerHTML来更改它,但是由于我们只想更改文本内容,所以让我们使用innerText属性。
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);
<p id="random-thing" />
https://stackoverflow.com/questions/71557759
复制相似问题