为什么我的输出未定义?

时间:2017-04-05 07:59:48

标签: javascript arrays json undefined

我用Javascript和HTML编写测验。对于统计数据,我想创建一个包含问题,用户答案和正确答案的表格。

是否有一个问题的多项选择答案我得到一个未定义的输出而不是用户的答案。

为什么我通过多项选择答案获得未定义的输出?一个答案的问题很有效。

我的代码:

$(function() {

  var quiz = [];
  var items = localStorage.getObject('tipkit');

  $.getJSON('api/quiz.json', function(data) {
    $.each(data.questions, function(i, f) {
      var tblRow = 
        "<tr>" + 
          // question id
          "<td>" + f.id + "</td>" +
          // question
          "<td>" + f.question + "</td>" +
          //user answers (id's and text)
          "<td>" + items['quest' + f.id] + ": " + f.answers[items['quest'+f.id]] + "</td>" + 
          //correct answers (id's and text)
          "<td>" + f.correct + ": " + f.answers[f.correct] + "</td>" + 
        "</tr>";
      $(tblRow).appendTo(".table tbody");
    });
  });

});

api.json

{
  "questions": [
    {
      "question":"Lorem ipsum dolor sit amet, consectetur adipiscing elit?",
      "linktitle":"Lorem ipsum",
      "id":1,
      "correct":"0",
      "type":"radio",
      "answers": [
        "Amet Commodo Magna Euismod",
        "Venenatis Euismod Commodo",
        "Bibendum Ullamcorper Ornare Vehicula Commodo",
        "Ipsum Fusce Sem Venenatis"
      ]
    },
    {
      "question":"Praesent commodo cursus magna, vel scelerisque nisl consectetur et?",
      "id":"2",
      "correct":"1, 3",
      "type":"checkbox",
      "answers": [
        "Dapibus Dolor Sem Egestas",
        "Vehicula Amet Parturient",
        "Commodo Parturient",
        "Tellus Dolor Ridiculus Etiam"
      ]
    }
  ]
}

localStorage的

key: tipkit
value: {"quest1":["1"], "quest2":["2","3"]}

2 个答案:

答案 0 :(得分:0)

"correct":"1, 3"

这条线正在制造问题。由于"1,3"无法解析为answers数组的索引。这就是f.answers[f.correct]返回undefined的原因。

您可以使用此方法获得多个答案:

function getMultipleAnswers(answers, indexes)
{
    var selectedAnswers = new Array();
        var indexe_array = indexes.split(',');
    for(var i = 0; i < indexe_array.length; i++)
    {
      selectedAnswers.push(answers[indexe_array[i]]);
    }
    return selectedAnswers;
}

答案 1 :(得分:0)

注意:

当我们要将JavaScript对象存储到HTML5 localStorage时,它会将JSON object转换为JSON string

&#13;
&#13;
var jsonObj = {"quest1":["1"], "quest2":["2","3"]};

console.log('typeof jsonObj: ' + typeof jsonObj);

// Put the object into storage
localStorage.setItem('tipkit', jsonObj);

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('tipkit');

console.log('typeof retrievedObject: ' + typeof retrievedObject);
&#13;
&#13;
&#13;

解决方案:

在存储JSON对象之前,我们必须stringify,在检索时我们必须parse

<强>样本

&#13;
&#13;
var jsonObj = {"quest1":["1"], "quest2":["2","3"]};

console.log('typeof jsonObj: ' + typeof jsonObj);

// Put the stringify object into storage
localStorage.setItem('tipkit', JSON.stringify(jsonObj));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('tipkit');

console.log('typeof retrievedObject: ' + typeof retrievedObject);

// Parse the JSON String.
console.log(JSON.parse(retrievedObject));
&#13;
&#13;
&#13;