从数组JavaScript中的数组调用带索引的数组元素

时间:2018-02-15 10:16:18

标签: javascript arrays for-in-loop

我想在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]);时会出现未定义。 我尝试了很多选项,但主要问题是在更改config时,在不更改main的情况下将问题与答案分开并在动态上添加问题+答案。 如果你能帮助我,我会非常感激。

谢谢!

3 个答案:

答案 0 :(得分:0)

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"
    ]
  ]
}

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

我使用了Tushar所说的内容:

  

我建议存储问题&同一个对象的答案。 { 题:   “abc”,答案:[“abc”,“def”,ghi“],正确:0}。

由于