0
votes

Comment récupérer tous les index qui correspondent à la condition en JavaScript?

J'ai besoin d'obtenir les index des éléments en question.Options grérailles qui ont "correct: vrai" sur eux. Il ne renvoie que le premier index (en raison de FINDIDEX), doit récupérer tous les index qui correspondent (pour des questions avec plus d'une réponse). Je devra ensuite ajouter un à chacun des index pour la matrice CorrectswerOptions pour passer à une autre fonction. Voici mon code.

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;
}


1 commentaires

Vérifiez ma réponse @Integal @Integal, cela vous donnera directement la matrice d'index d'options correctes + 1


4 Réponses :


0
votes

0
votes

question.option.filter (élément => item.correct) .map ((élément, index) => Index + 1);


2 commentaires

Merci! Fonctionne parfaitement.


Oui. Merci encore.



0
votes

Utilisez la fonction suivante, est adapté de Ce xxx


0 commentaires

1
votes

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)


0 commentaires