首页 > 解决方案 > 如何检索与 JavaScript 中条件匹配的所有索引?

问题描述

我需要获取 issue.options 数组中具有“正确:真”的项目的索引。它只返回第一个索引(因为 findIndex),需要检索所有匹配的索引(对于有多个答案的问题)。然后,我需要为每个索引添加一个正确答案选项数组以传递给另一个函数。这是我的代码。

getCorrectAnswers(question: QuizQuestion) {
  console.log(question.options.findIndex(item => item.correct));
  const identifiedCorrectAnswers = question.options.filter(item => item.correct);
  this.numberOfCorrectOptions = identifiedCorrectAnswers.length;

  // need to push the correct answer option numbers here!
  this.correctAnswers.push(identifiedCorrectAnswers);
  // pass the correct answers
  this.setExplanationAndCorrectAnswerMessages(this.correctAnswers);

  return identifiedCorrectAnswers;
}

标签: javascriptangular

解决方案


function funcWhichNeedCorrectAnswerIndicesPlusOne(indices) {
 console.log(indices)
}

function getCorrectAnswers(question) {
  funcWhichNeedCorrectAnswerIndicesPlusOne(question.options
     .filter(option => option.correct)
     .map(option => question.options.indexOf(option) + 1)
  )   
}

const question = {
 options: [{
   correct: true
  }, {
    correct: false
  }, {
    correct: true
  }
]}

getCorrectAnswers(question)


推荐阅读