javascript - 如何更新多个数组元素

标签 javascript arrays

在我的 Javascript Hangman 游戏的冲刺阶段。剩下的任务是当用户猜测神秘单词中多次包含的字母时处理更新破折号(字母的占位符)。

代码知道猜测的字母在神秘单词(变量名称:totalCorrect)中出现了多少次,以及这些字母在神秘单词(数组名称:combineDashes)中的索引(数组变量名称:indices)。

当用户猜测单词中只出现一次的字母时,我使用以下代码来更新神秘单词中的破折号,但在存在多个实例时无法弄清楚如何更新破折号占位符神秘词中的字母(索引包含多个索引)。

// replaces dash with the correctly guessed letter in the mystery word.
combineDashes[indices] = letter;    

完整代码如下:

// JavaScript Document


$(document).ready(function() {      // upon page load

        var badGuesses;   // reset bad guess counter
        var theWord;        // defines variable globally
        var combineDashes;   // defines variable globally
        var letter;     // defines variable globally
        var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Z"];   // array of letters to choose
        $("#lettersRemaining").html(alphabet);  // gets elements of the alphabet array and displays on UI


//  N E W  G A M E  B U T T O N   C L I C K E D

    $("#newGame").click(function() {    // when user clicks on Start New Game button...

        $("#status").hide();   // upon game reset hide the status section stating game over
        var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Z"];   // reset array of letters to choose from

        $("#hangmanGuy").html('<img src="img/Hangman-0.png" id="hangmanImg" alt="pic of hangman no limbs" width="144" height="216">'); // reset hangman image
        badGuesses = 0;   // reset guess counter which is used later

        var wordCollection = ["MANSION", "STATUE", "GORILLA", "NOTEBOOK", "SMARTPHONE", "ILLUSTRATION", "PHOTO", "ELEGANT", "ARBORIST", "KEYBOARD", "CALENDAR", "CAPITAL", "TEXTBOOK", "HORRIBLE", "LIBRARY"];  //  array of words the computer will randomly choose from

        theWord = wordCollection[Math.floor(Math.random()*wordCollection.length)]; // randomly selects a word
            console.log("theWord is ....");
            console.log(theWord);

        var theWordLength = theWord.length;     // Get number of characters in randomly selected word to know how many dashes to display
            console.log("theWordLength is ....");
            console.log(theWordLength);

        // D I S P L A Y  D A S H E S

        combineDashes = []; // creates an array to hold the number of dashes inside the for loop

        for (var i = theWordLength; i > 0; i--) 
            {
                combineDashes.push(" - ");  // each loop through adds a dash to the array
            }

        combineDashes.join(" ");  // joins cumulative dashes and converts to a string

        $("#dashes").html(combineDashes); // displays dashes on UI
                console.log("combineDashes is...");
                console.log(combineDashes);

    });


// G U E S S   L E T T E R  C L I C K E D

    $("#guessLetter").click(function() {    // when user clicks on the Guess Letter button pass in theWord value ....
                    console.log(combineDashes);

        var letter = $("#theLetter").val().toUpperCase();   // gets the letter the user is guessing & makes uppercase
            console.log("letter is ...");
            console.log(letter);

        // Is the letter a good or bad guess?
        var indices = [];   // new array to capture indices of all letters contained in the word

        var idx = theWord.indexOf(letter);

        while (idx !== -1) {                    // loops thru to find all letters in the word
            indices[indices.length] = idx;
            idx = theWord.indexOf(letter, idx + 1);
        }
            console.log("indices of letter guess contained in the word");
            console.log(indices);

        var totalCorrect = indices.length; // captures how many letters guessed were correct
            console.log("totalCorrect letters...");
            console.log(totalCorrect);

    //  F O R  B A D  G U E S S E S
        if (indices.length === 0)   //  if bad guess 
            {
                badGuesses++;    // increment bad guess counter
                $("#status").show();
                $("#status").html("Sorry, " + letter + " is incorrect. Try again.");  // status message displays
                console.log("Total badGuesses...");
                console.log(badGuesses); 

                //  remove guessed letter from alphabet
                var alphaIndex = alphabet.indexOf(letter);      // gets index of letter in alphabet
                alphabet.splice(alphaIndex,1);  // removes the letter from the alphabet array
                console.log("alphabet index of letter guessed...");
                console.log(alphaIndex);
                $("#lettersRemaining").html(alphabet);  // refreshes letters remaining

            // display correct hangman image based on how many bad guesses
                    if (badGuesses === 1) 
                    {
                        $("#hangmanGuy").html('<img src="img/Hangman-1.png" id="hangmanImg" alt="pic of hangman 1 limb" width="144" height="216">');
                    }
                    else if (badGuesses === 2)
                    {
                            $("#hangmanGuy").html('<img src="img/Hangman-2.png" id="hangmanImg" alt="pic of hangman 2 limbs" width="144" height="216">');
                    }
                    else if (badGuesses === 3)
                    {
                            $("#hangmanGuy").html('<img src="img/Hangman-3.png" id="hangmanImg" alt="pic of hangman 3 limbs" width="144" height="216">');
                    }
                    else if (badGuesses === 4)
                    {
                            $("#hangmanGuy").html('<img src="img/Hangman-4.png" id="hangmanImg" alt="pic of hangman 4 limbs" width="144" height="216">');
                    }
                    else if (badGuesses === 5)
                    {
                            $("#hangmanGuy").html('<img src="img/Hangman-5.png" id="hangmanImg" alt="pic of hangman 5 limbs" width="144" height="216">');
                    }
                    else if (badGuesses === 6)
                    {
                            $("#hangmanGuy").html('<img src="img/Hangman-6.png" id="hangmanImg" alt="pic of hangman 6 limbs" width="144" height="216">');
                            $("#status").html("Game Over. Sorry, you didn't win. Click Start New Game and try again.");  // status message displays
                    }
            }
        //  F O R  G O O D  G U E S S E S
        else
            {
                //  remove guessed letter from alphabet
                var alphaIndex = alphabet.indexOf(letter);      // gets index of letter in alphabet

                alphabet.splice(alphaIndex,1);  // removes the letter from the alphabet array
                    console.log("alphabet index of letter guessed...");
                    console.log(alphaIndex);

                $("#lettersRemaining").html(alphabet);  // refreshes letters remaining

                console.log(indices[0]); // gives value of the indexes array position 0
                console.log(indices[1]); // gives value of the indexes array position 1
                console.log(indices[2]); // gives value of the indexes array position 2
                console.log(indices[3]); // gives value of the indexes array position 3
                console.log(indices[4]); // gives value of the indexes array position 4
                console.log(indices[5]); // gives value of the indexes array position 5
                console.log(indices[6]); // gives value of the indexes array position 6 
            }


            // R E P L A C E  D A S H E S  W I T H  L E T T E R

                    // if there's only one instance of the letter in the word... 
                    if (totalCorrect === 1) {   
                        combineDashes[indices] = letter;        
                        console.log(letter);
                        console.log(combineDashes);
                    }

                    else // if there are multiple instances of the letter in the word...
                    {
                        letterInWordIndex0 = indices[0];  // assigns value of index to variable
                        letterInWordIndex1 = indices[1]; // assigns value of index to variable
                        letterInWordIndex2 = indices[2]; // assigns value of index to variable

                        combineDashes[letterInWordIndex0] = letter; // replaces dash with letter
                        combineDashes[letterInWordIndex1] = letter; // replaces dash with letter
                        combineDashes[letterInWordIndex2] = letter; // replaces dash with letter
                    }
                //  D I S P L A Y  S T A T U S   M E S S A G E
                $("#dashes").html(combineDashes); // 
                $("#status").show();

// HUNG UP HERE
                combineDashes.find(" - ");

                if (noMoreDashes = []) {  // ?? HOW TO SAY NO DASHES REMAIN ?
                    $("#status").html("YOU WIN! Click Start New Game to play again.");  // status message displays
                    }
                else
                {
                    $("#status").html(letter + " is correct! Go again.");  // status message displays
                }


    });

});     

最佳答案

对于当 totalCorrect 为 1 或更大时,您可以使用这段代码:

indices.forEach(function (index) {
    combineDashes[index] = letter; 
});

然后你这样做:

combineDashes.find(" - ");

但是您没有捕获它给出的结果。此外,find 需要一个回调函数。您可以使用 includes 代替,并使用 ! 运算符(即“not”)将其合并到后面的 if 中:

if (!combineDashes.includes(" - ")) {
    $("#status").html("YOU WIN! Click Start New Game to play again.");
}

如果您的浏览器不支持includes,则使用indexOf,如下所示:

if (combineDashes.indexOf(" - ") == -1) {
    $("#status").html("YOU WIN! Click Start New Game to play again.");
}

请注意,您的代码中还存在其他几个问题。太长了,无法完整分析,但例如:

combineDashes.join(" "); 

...什么也不做。因为join返回结果——它不会修改combineDashes。而是在您传递要显示的地方使用它:

$("#dashes").html(combineDashes.join(" "));

代码有很多重复。尝试重用代码。例如,这个:

if (badGuesses === 1) 
{
    $("#hangmanGuy").html('<img src="img/Hangman-1.png" id="hangmanImg" alt="pic of hangman 1 limb" width="144" height="216">');
}
if (badGuesses === 2) 
    // ...etc

...可以写成:

if (badGuesses <= 6) {
    $("#hangmanGuy").html('<img src="img/Hangman-' + badGuesses 
        + '.png" id="hangmanImg" alt="pic of hangman ' + badGuesses 
        + ' limb" width="144" height="216">');
}
if (badGuesses >= 6) {
    $("#status").html("Game Over. Sorry, you didn't win. Click Start New Game and try again.");
}

关于javascript - 如何更新多个数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40833697/

相关文章:

c++ - 如何检查一个数字被输入了多少次

javascript - 我在 javascript 中有一个低温数组,我需要获得最低温度,所以我使用了 min.math 函数

javascript - 输入的总和数组

javascript - 根据随机数组结果播放特定的声音?

objective-c - 将字节的 NSArray 转换为 NSData

java - 我需要找到用户输入的特定变量,但我不明白如何

javascript - 正则表达式匹配前面或后面没有其他字符的确切单词

javascript - 如何将矢量(X,Y)位置转换为纬度/经度坐标? JavaScript

javascript - 查找给定字符串的数组匹配元素的最佳方法

ios - 如何在 swift 中对 CoreData 的双属性求和