【问题标题】:IndexOf returns undesirable -1IndexOf 返回不受欢迎的 -1
【发布时间】:2020-10-16 03:53:59
【问题描述】:

我有一个由 JavaScript 对象组成的数组。每次在我的initQuestion 函数中调用一个对象时,我都想在数组中找到该对象的索引。我正在使用.indexOf 数组方法尝试查找索引,不幸的是,indexOf 方法返回-1,这不是预期的效果。

我还有一个随机函数,它从数组中随机选择一个对象,这可能是我发现 indexOf 函数难以使用的原因吗?

/// Quiz Night (Who Wants to be A Millionaire Version)
(function() {
  function Quiz(question, options, answer) {
    this.question = question;
    this.options = options;
    this.answer = answer;
  };

  // let displayQuestion = document.getElementById('question_text');
  // displayQuestion.innerHTML = "test";

// HTML Selectors declerations 
  let headingQuestion, ul, displayAnswer, quizForm;
  headingQuestion = document.getElementById('question');
  ul = document.getElementById('question_text');
  displayAnswer = document.getElementById('display_answer');
  quizForm = document.getElementById('quizForm');

Quiz.prototype.initQuestion = function() {
    headingQuestion.innerHTML = this.question;
    for (let i = 0; i < this.options.length; i++) {
      ul.innerHTML += `<li>${i}: ${this.options[i]}</li>`;
    };

    quizForm.addEventListener("submit", (e) => {
      e.preventDefault();
      let textAnswer = document.getElementById('textAnswer').value;
      let userAnswer = parseInt(textAnswer);
      if (userAnswer === this.answer) {
        displayAnswer.innerHTML = `\n${this.options[userAnswer]}, is the correct Answer`;
      } else {
        displayAnswer.innerHTML = `\n${this.options[userAnswer]} is incorrect.`;
      };

      console.log(allQuestions.indexOf(this.question));
    });
  };

  // Store quiz questions in a array or data table. 
  let q1 = new Quiz("Which one of the following names was not a member of the famous English rock band 'The Beatles'?", ['Rod Stewart', 'Ringo Starr', 'George Harrison', 'Paul McCartney'], 0);
  let q2 = new Quiz("Which US state is known as the Grand Canyon State?", ['Arkansas', 'Arizona', 'Colorado', 'Massachusetts'], 1);
  let q3 = new Quiz("What is the smallest country in the world?", ['Monaco', 'Singapore', 'Vatican', 'Fiji'], 2);
  let q4 = new Quiz("Choose the world's deepest river?", ['Amazon River', 'Yangtze River', 'Nile River', 'Congo River'], 3);

  let allQuestions = [
    q1,
    q2,
    q3,
    q4
  ];

  let n = Math.floor(Math.random() * allQuestions.length);
  allQuestions[n].initQuestion();
})();
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <!-- Bootstrap Link -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  <!--Custom style sheet -->
  <link rel="stylesheet" href="style.css">


  <!--Bootstrap Javascript-->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>


  <title>Section Five</title>

</head>

<body>
  <div class="container">
    <div class="row">
      <h1></h1>
    </div>
    <div class="row">
      <h3 id="question"></h3>
    </div>
    <div class="row">
      <ul id="question_text">
        <!--For Loop insert here-->
      </ul>
    </div>
    <div class="row">
      <p id="display_answer"></p>
    </div>
    <form id="quizForm" class="quizForm">
      <div class="form-group">
        <input type="text" id="textAnswer">
      </div>
      <button type="submit">Submit</button>
    </form>
    <button type="button">Next Question</button>
  </div>
</body>

<script src="app.js"></script>

</html>

【问题讨论】:

  • 谢谢,已添加 sn-p。

标签: javascript arrays object methods


【解决方案1】:

allQuestions 中的条目是 Quiz 实例,但 this.question 是一个字符串,因此您是在比较苹果和橙子。你可能想要:

const index = allQuestions.indexOf(this);

(也许改为allQuizzes?)

或者只知道它是否存在:

const found = allQuizzes.includes(this);

或者,如果您想在allQuizzes 中找到具有匹配问题的Quiz 实例,请使用find 而不是indexOf

const quiz = allQuizzes.find(({question}) => question === this.question);

(或使用findIndex 查找其索引。)

【讨论】:

    【解决方案2】:

    this.question 是问题的文本(字符串),但allQuestionsQuiz 对象的数组,而不是字符串。

    由于thisQuiz 对象,您应该在数组中搜索它:

    console.log(allQuestions.indexOf(this));
    

    【讨论】:

      猜你喜欢
      • 2019-07-09
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多