// Выбираем случайное слово из массива var words = ["программа", "процессор", "прекрасный", "робот"]; var word = words[Math.floor(Math.random() * words.length)]; // Неугаданные буквы var remainingLetters = word.length; // Попытки var remainingAttempt = 3; // Создаем массив ответов и заполняем его var answerArray = []; for (var i = 0; i < word.length; i++) { answerArray[i] = "_"; }; // Основной цикл программы while (remainingLetters > 0 && remainingAttempt > 0) { alert('Текущее слово : ' + answerArray.join(" ")); var guess = prompt("Угадайте букву или нажмите отмена для выхода из игры."); guess = guess.toLowerCase(); console.log(guess); if (guess === null) { break; } else if (guess.length !== 1) { alert("Пожайлуста, введите только одну букву."); } else { for (var j = 0; j < word.length; j++) { if (word[j] === guess) { if (answerArray[j] === '_') { answerArray[j] = guess; remainingLetters--; alert("Вы угадали букву!"); } else { alert("Вы уже угадали эту букву!"); } } else { remainingAttempt--; alert('Попыток осталось ' + remainingAttempt); break; } } } } alert('Результат : ' + answerArray.join(" ")); alert("Конец игры! Было загадано слово " + word); 

I can not understand why in the example the condition if (word[j] === guess) becomes equal to false , although the letter is entered which is in the word and goes to its else . If you remove the else , then everything works as it should. Help me to understand.

  • And if === replaced by == ? - ArchDemon
  • @alexx Try word [j] === guess [0] - Vlad from Moscow
  • one
    Nah, what is it here ===, everything is simpler, when you take the steps to spell, your cycle goes through the whole word every attempt and from this, even if you guess one letter, the rest will be false - arkadij_ok
  • @arkadij_ok, write an answer - Grundy
  • one
    in general, at the moment it is calculated that the letters will be guessed in order, that is, you cannot guess the last letter without guessing all the letters in front of it. it is necessary to completely revise the logic of verification - Grundy

2 answers 2

The whole point is that your for loop runs through the whole word, and if you guess the letter, it still checks the others, where it returns false

    The == operator compares for equality)) with type conversion, but === compares for identity.
    == and === differences in javascript

    • one
      in this case it does not matter - Grundy
    • Please try to publish detailed answers containing a specific example of the minimum solution, supplementing them with a link to the source. Answers –references (as well as comments) do not add knowledge to the Runet. - Nicolas Chabanovsky