Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

javascript - 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
    },
]

I'm trying this way but return -1:

console.log(questions.findIndex(value => value.answers.indexOf() === 'Apis'));

For example if wanna get the indexOf 'Apis', i get -1.

I'm trying to compare 'CorrectIndex' value with index of answers array value and return if its correct or not.

question from:https://stackoverflow.com/questions/65848195/how-can-i-get-the-index-of-array-element-inside-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You just used indexOf in a wrong way. That's quite simple to fix:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...