【问题标题】:How can I get the index of array element inside object?如何获取对象内数组元素的索引?
【发布时间】:2021-01-22 15:40:13
【问题描述】:
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”值与答案数组值的索引进行比较,并返回是否正确。

【问题讨论】:

  • questions 是一个数组,它可能包含多个项目。如果有多个应该怎么办?在获得答案索引之前,我们是否知道使用什么索引来获得正确的问答项目?
  • value.answers.indexOf() 缺少参数。为什么要尝试将数字与字符串进行比较?
  • 您的问题缺乏上下文。 'Apis' 来自哪里?您如何知道需要将其与 questions 中的哪个问题进行比较?

标签: javascript html indexof


【解决方案1】:

如果我理解正确,您想获取此对象的answers 数组中的元素索引。 试试这个:

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

这将为您提供一个值为“Apis”的索引数组。

如果你在同一个数组中有重复的值,你可以这样做:

console.log(questions.map(value => [value.answers.indexOf('Apis')]));

这将存储一个数组,您可以在其中获取每个对象的“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));

【讨论】:

  • 那是因为“Apis”是数组的第一个元素。
  • 你想要答案数组中包含 API 的对象的索引吗?
  • 如果正确回答“问题”“蝴蝶的学名是什么?”是 Rhopalocera,因为您的“正确索引”设置为 3。索引为 3 表示这是数组的第 4 个元素。
  • 添加其他值仍然返回 0
  • 我已经稍微修改了我的答案。看看,让我知道这是否有效。
【解决方案2】:

您只是以错误的方式使用了 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 是一个函数并接收一个字符串。

【讨论】:

  • value.answers.indexOf('Apis')>-1
  • @SulmanMalik 你能看看我的 sn-p 吗?我更新了它,它现在可以工作了
【解决方案3】:

你为什么要比较value.answers.indexOf()

正确的语法应该是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多