使用数组中数组的索引调用数组元素 JavaScript

Calling array element with index from an array inside the array JavaScript

我想在 JS 中制作一个调查应用程序,我的主要代码如下:

for(var questionNumber in questionsAndAnswers.allQuestions){
      for(var i in questionsAndAnswers.allQuestions[questionNumber]){
        console.log(questionsAndAnswers.allQuestions[questionNumber].question);
        console.log(questionsAndAnswers[questionNumber+1]);
    } 
}

配置中的这段代码:

const questionsAndAnswers = {
    "allQuestions": [
        { "question": "Write your first question here",
        },
        { "question": "Write your second question here",
        },
        { "question": "Write your third question here",
      }
     ],
    "answerOne": [
        "1.This is the first answer",
        "1.This is the second answer",
        "1.This is the third answer"
        ],
    "answerTwo": [
        "2.This is the first answer",
        "2.This is the second answer",
        "2.This is the third answer"
      ],
     "answerThree": [
        "3.This is the first answer",
        "3.This is the second answer",
        "3.This is the third answer"
      ]
}

然后是这样的:

Write your first question here
undefined
Write your second question here
undefined
Write your third question here
undefined

我想这样做:当第一个问题被问到时,只有第一个答案出现,但是当我调用 console.log(questionsAndAnswers[questionNumber+1]);Undefined 时出现。 我尝试了很多选项,但主要问题是将问题与答案分开,并在 config 更改时动态添加问题 + 答案,而不更改 main。 如果你能帮助我,我将非常感激。

谢谢!

questionNumber是一个表示索引的整数。因此,对于第一项 questionNumber === 0,您正试图从 questionsAndAnswers[0 + 1] === questionsAndAnswers[1] 获得答案。由于您的对象上没有 属性 "1",因此它是未定义的。

如果你想使用与此类似的数据结构,我建议如下:

for(var questionNumber in questionsAndAnswers.allQuestions){
  console.log(questionsAndAnswers.allQuestions[questionNumber].question);
  for(var i in questionsAndAnswers.allAnswers[questionNumber]){
    console.log(questionsAndAnswers[questionNumber][i]);
  } 
}

const questionsAndAnswers = {
  "allQuestions": [
    { "question": "Write your first question here" },
    { "question": "Write your second question here" },
    { "question": "Write your third question here" }
  ],
  "allAnswers": [
    [
      "1.This is the first answer",
      "1.This is the second answer",
      "1.This is the third answer"
    ],
    [
      "2.This is the first answer",
      "2.This is the second answer",
      "2.This is the third answer"
    ],
    [
      "3.This is the first answer",
      "3.This is the second answer",
      "3.This is the third answer"
    ]
  ]
}

但是,我鼓励您探索组织数据结构的不同方式,因为这种方式看起来有点奇怪。也许尝试为问题和答案创建单独的对象,或者在问题下嵌套答案。

我认为您应该重新考虑您的数据模型。 您的 questionsAndAnswers 是一个对象,这意味着您不是通过整数而是通过键("answerOne"、"answerTwo"、...)访问问题。 因此 questionsAndAnswers[questionNumber+1] 不起作用。 它必须类似于 questionsAndAnswers["answerOne"].

但是我建议您将答案保存在您的问题对象中。

{
    "question": "Write your first question here",
    "answers": [...]
}

我用了Tushar说的:

I suggest to store the question & answers in same object. { question: "abc", answers: ["abc", "def", ghi"], correct: 0}.

谢谢