[英]How can I get the index of array element inside object?
const questions = [
{
"question": "What is the scientific name of a butterfly?",
"answers": ["Apis", "Coleoptera", "Formicidae", "Rhopalocera"],
"correctIndex": 3
},
{
"question": "How hot is the surface of the sun?",
"answers": ["1,233 K", "5,778 K", "12,130 K", "101,300 K"],
"correctIndex": 1
},
]
我正在嘗試這種方式但返回-1:
console.log(questions.findIndex(value => value.answers.indexOf() === 'Apis'));
例如,如果想獲得 indexOf 'Apis',我得到 -1。
我正在嘗試將“CorrectIndex”值與答案數組值的索引進行比較,並返回它是否正確。
如果我理解正確,您想獲取此 object 的answers
數組中的元素索引。 嘗試這個:
console.log(questions.map(value => value.answers.indexOf('Apis')));
這將為您提供一個值為“Apis”的索引數組。
如果您在同一個數組中有重復的值,您可以這樣做:
console.log(questions.map(value => [value.answers.indexOf('Apis')]));
這將存儲一個數組,您可以在其中獲取每個 object 的“Apis”的索引。
我正在嘗試將“CorrectIndex”值與答案數組值的索引進行比較,並返回它是否正確。
const questions = [ { "question": "What is the scientific name of a butterfly?", "answers": ["Apis", "Coleoptera", "Formicidae", "Rhopalocera"], "correctIndex": 3 }, { "question": "How hot is the surface of the sun?", "answers": ["1,233 K", "5,778 K", "12,130 K", "101,300 K"], "correctIndex": 1 }, ] console.log(questions.map(value => value.answers.indexOf('Apis') === value.correctIndex));
您只是以錯誤的方式使用了 indexOf 。 這很容易解決:
const questions = [ { question: "What is the scientific name of a butterfly?", answers: ["Apis", "Coleoptera", "Formicidae", "Rhopalocera"], correctIndex: 3 }, { question: "How hot is the surface of the sun?", answers: ["1,233 K", "5,778 K", "12,130 K", "101,300 K"], correctIndex: 1 } ] questions.forEach(question => { console.log(question.answers.indexOf('Apis')) });
意識到 indexOf 是一個 function 並接收一個字符串。
你為什么要比較value.answers.indexOf()
正確的語法應該是
console.log(questions.findIndex(value => value.answers.indexOf('element')));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.