N
N
Nikita Petrov2021-01-24 17:38:11
JavaScript
Nikita Petrov, 2021-01-24 17:38:11

Why does .includes return false?

The problem is that .includes returns false when checking for the presence of an array element that the user should enter, even though this element is in the array

var answers = [
  ["Зимой и летом одним цветом.", "елка", "ель"],
  ["Речка спятила с ума — по домам пошла сама." , "водопровод" , "канализация"],
  ["Орехов не ест, сахара не просит, а щипцы с собой носит." , "рак" , "краб"]
  ];
  var trueAnswers = 0
  var puzzle = 0
  function findAnswer(userInput){
    if (answers.includes(userInput, 1)){
    //возвращает false при проверке элемента 
      puzzle++
      trueAnswers++
      return alert("Вы угадали.")
    } else {
      puzzle++
      return alert("Вы не угадали.")
    }
  }
  for (var i = 0; i < 3; i++){
    var userInput = prompt((answers[puzzle][0])).toLowerCase()
    findAnswer(userInput)
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-01-24
@zzettaqq

Includes returns false when checking for the presence of an array element if there is no such element in the array .
What you are checking you did not provide, so this is all that can be answered for such a question.
Actually, of course, the reason is that you're checking an array of arrays for a string, but that doesn't change the need to ask questions normally.
You need to change the data structure and separate questions from answers. And in findAnswer, also pass the number of the question in order to search only among its answers. Well, or immediately transfer an array of correct answers there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question