skip to Main Content

I have here an array consisting of a word and a hint for the word (made the hints very quickly please do not judge). Once the random word is generated, I’d like the hint corresponding to that word be shown in a div I created. I attempted using inner.HTML, but whenever I do, "undefined" comes up? Does anyone have any input? Much thanks.

yet = document.querySelector('.clue-text')

const wordList = [
    {
        word: "Grand",
        hint: "Something large"
      },
      {
        word: "Drank",
        hint: "An act of consuming liquids"
      }
]

function randomWord() {
    let random = Math.floor(Math.random() * wordList.length);
    console.log(random, wordList[random]);
    yet.innerHTML = random.hint;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="clue-text" class="clue-text">Hint goes here</div>
</body>
</html>

2

Answers


  1. You’re trying to access the hint property using random.hint, but it should be wordList[random].hint. Here’s the fixed version:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div id="clue-text" class="clue-text">Hint goes here</div>
        <button onclick="randomWord()">Get Random Word</button>
        
        <script>
            const yet = document.querySelector('.clue-text');
    
            const wordList = [
                {
                    word: "Grand",
                    hint: "Something large"
                },
                {
                    word: "Drank",
                    hint: "An act of consuming liquids"
                }
            ];
    
            function randomWord() {
                let random = Math.floor(Math.random() * wordList.length);
                console.log(random, wordList[random]);
                yet.innerHTML = wordList[random].hint;
            }
        </script>
    </body>
    </html>
    Login or Signup to reply.
  2. Access the hint using wordList[random].hint.

    function randomWord() {
        let random = Math.floor(Math.random() * wordList.length);
        console.log(random, wordList[random]);
        yet.innerHTML = wordList[random].hint;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search