我正在检查两个数组中是否有相同的字母,但是当有多个相同的字母时似乎无法工作

I am checking if there are the same letters in two arrays, but can't seem to work when there are multiple same letters

提问人:Moad Bouzidi 提问时间:4/15/2023 最后编辑:user16217248Moad Bouzidi 更新时间:5/12/2023 访问量:31

问:

所以我被分配了一个任务(检查图像),我需要做一个猜谜游戏。它被指定为几乎所有东西都使用数组,所以这是我的问题。当我检查重复项(和 中的相同字母)时,代码一直工作到出现第二个相同的字母 - 在这种情况下是倒数第二个索引上的 E。任何线索我如何解决这个问题,甚至是工作表的解决方案?guessedLetterscorrectWord

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        .red {
            background-color: red;
        }

        .green {
            background-color: green;
        }

        p {
            width: 100px;
            height: 20px;
            background-color: black;
            color: white;
        }

        #msgOutput {
            background-color: wheat;
            color: black;
        }
    </style>
</head>
<body>
    
    <input type="text" id = "txtInp">
    <button>?</button>

    <p id = "msgOutput"></p>

    <p class="green"></p>
    <p class="green"></p>
    <p class="green"></p>
    <p class="green"></p>
    <p class="green"></p>

    <script>
        let correctWord = ["B", "E", "R", "G", "E", "N"];
        let input = document.querySelector("input");
        let guessBtn = document.querySelector("button");


        let guessedLetters = []
        let correctlyGuessedLetters = []

        const checkWord = () => {
            let guessedLetter = input.value.toUpperCase()
            guessedLetters.push(guessedLetter)
            

            for(let i = 0; i < guessedLetter.length; i++){
                for(let j = 0; j < correctWord.length; j++){
                    if(guessedLetter[i] == correctWord[j]){
                        console.log(`${guessedLetter[i]} og ${correctWord[j]} er like`)
                        correctlyGuessedLetters[correctWord.indexOf(guessedLetter[i])] = guessedLetter[i]
                    } else {
                        console.log(`${guessedLetter[i]} og ${correctWord[j]} er ikke like`)
                    }
                }
            }

            input.value = ""
            console.log(correctlyGuessedLetters)
        }


        guessBtn.addEventListener("click", checkWord)
    </script>
</body>
</html>

The task for the assignment

我本来希望在数组中得到,但它似乎不适用于带有双字母的单词?correctWordcorrectlyGuessedLetters

数组输入 dom-events variable-assignment

评论

0赞 Tim Roberts 5/12/2023
correctWord.indexOf(guessedLetter[i])总是要返回第一个匹配项的索引。在这种情况下,您根本不需要它。你已经知道你正在查看的字母的索引 -- 它在 .j

答: 暂无答案