javascript - 如何检索与 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;
}
解决方案
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)
推荐阅读
- google-cloud-platform - 在 GKE 上为 Hashicorp Vault 配置插件目录
- angular - 为什么 Angular 8 所需的验证与 ngValue 的行为不同?
- node.js - nginx 位置未正确加载
- c# - C#在鼠标移动时隐藏工具提示并在鼠标悬停时再次显示它而不离开控制
- android - 检查地图上的标记是否已被删除 - Android
- r - 为什么 dplyr 过滤器没有捕获 NA
- javascript - 从 wordpress 网页创建可下载的 PDF
- windows - pthread_cond_wait 的 Win32 等效 API
- ruby - Sprintf 浮点数行为从 Ruby 2.3 更改为 2.4
- javascript - 我无法连接到 mongodb atlas cluster。我得到了 MongooseError 如下