繁体   English   中英

如何获取 object 中数组元素的索引?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM