代码之家  ›  专栏  ›  技术社区  ›  integral100x

JavaScript检索符合条件的所有索引

  •  -1
  • integral100x  · 技术社区  · 5 年前

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

    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;
    }
    
    2 回复  |  直到 4 年前
        1
  •  1
  •   Vishal Sharma    5 年前

    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)
        2
  •  0
  •   AzloD    5 年前
        3
  •  0
  •   Aakash Garg    5 年前

    question.options.filter(item=>item.correct).map((item,index)=>指数+1);

        4
  •  0
  •   Malintha Ranasinghe    5 年前

    使用以下功能,改编自 this

    function getAllIndexes(arr, val) {
        var indexes = [], i;
        for(i = 0; i < arr.length; i++)
            if (arr[i] === val)
                indexes.push(i);
        return indexes;
    }