【问题标题】:Choose and delete random word from array in Javascript [closed]在Javascript中从数组中选择并删除随机单词[关闭]
【发布时间】:2021-05-06 11:52:02
【问题描述】:

我正在尝试用 Javascript 重新制作我用 Python 制作的文字游戏。我在做一些基本的事情时遇到了麻烦。

脚本应该加载一个单词列表,当您单击按钮时,它应该显示列表中的一个随机单词。我尝试了几种方法,但在再次单击按钮时显示的索引号并没有刷新。

所以我在这个阶段的问题是:如何通过单击选择随机数组项,然后将其删除,以便再次单击时不会再次出现。我确实想在之后添加显示单词和 TTS 的时间限制,但这将在稍后进行。

<html>
<head>
    <title>Aliyah's dictee spel</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="header">
    <h1>Hej! Velkommen til Aliyahs diktee!</h1>
    </div>
    <div id="Random_word">
        <h2 id="Empty">Click new word to start</h2>
        <button id="refresh_word">new word</button>

    </div>
    <input type="text" id="input1" />
    <input type="submit" name="ok" value="ok"/>
    <script>
        
    var words = ["test1", "test2", "test3"];
    var wordsCorrect = 0;
    var wordsWrong = 0;

    newWord(words)
    {
        var random = Math.floor(Math.random() * words.length);
        document.getElementById("Empty").innerHTML = random;
    };
    document.getElementById("refresh_word").addEventListener("click", newWord());

    

    </script>
</body>
</html>

【问题讨论】:

  • () 在函数引用后面总是立即调用该函数。

标签: javascript arrays random


【解决方案1】:

替换:

document.getElementById("refresh_word").addEventListener("click", newWord());

与:

document.getElementById("refresh_word").addEventListener("click", () => newWord(words));

您还缺少 newWord 声明前面的 function 关键字和 words[random] 而不仅仅是 random 这是一个索引。

var words = ["test1", "test2", "test3"];
var wordsCorrect = 0;
var wordsWrong = 0;

function newWord(words)
{
  var random = Math.floor(Math.random() * words.length);
  document.getElementById("Empty").innerHTML = words[random];
  words.splice(random, 1);
};
document.getElementById("refresh_word").addEventListener("click", () => newWord(words));
<div id="header">
<h1>Hej! Velkommen til Aliyahs diktee!</h1>
</div>
<div id="Random_word">
  <h2 id="Empty">Click new word to start</h2>
  <button id="refresh_word">new word</button>
</div>
<input type="text" id="input1" />
<input type="submit" name="ok" value="ok"/>

【讨论】:

  • 它甚至应该是() =&gt; newWord(words)。该事件不包含单词,因此应通过调用函数传递。
  • 是的,确实感谢您的指出
  • 然后在设置好DOM后加上words.splice(random, 1)就完成了“去掉之后再点击不会出现第二次”的问题。然后你“只是”需要处理数组为空时的情况。
  • 或者只是删除words 参数并使用全局变量。鉴于 OP 大概也想要正确/错误的计数,而且这些计数是全局的,似乎不值得仅仅通过 words
  • 谢谢大家!我是一个完全的菜鸟,我设法用 Python 做了一个很好的工作,我只是不懂 Javascript,但这对我有很大帮助!
猜你喜欢
  • 2012-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2013-04-07
相关资源
最近更新 更多