无法获取未定义的属性“userResponse”

时间:2016-10-31 18:50:23

标签: javascript json object nativescript

我试着通过构建一个travia游戏应用来学习nativescript。 我有一个问题json列表如下:

var questionsList20 = {"questions" : [{"question":"Taxing a commodity at the production level decreases supply.","correctAnswer":"answerOne","answerOne":"True","answerTwo":"False","answerThree":"Uncertain","answerFour":"None of the above","userResponse":"","explanationTwo":"True","grade":""},{"question":"The circular flow depicts the alternative combination of goods and services an economy \tcan produce at a point in time.","correctAnswer":"answerTwo","answerOne":"True","answerTwo":"False","answerThree":"Uncertain","answerFour":"None of the above","userResponse":"","explanationTwo":"False","grade":""},{"question":"Demand is inelastic if elasticity of demand < 0.","correctAnswer":"answerTwo","answerOne":"True","answerTwo":"False","answerThree":"Uncertain","answerFour":"None of the above","userResponse":"","explanationTwo":"False","grade":""},{"question":"Elasticity of demand measures the percentage change in the quantity demand of a commodity as a result of a given percentage change in price.","correctAnswer":"answerTwo","answerOne":"True","answerTwo":"False","answerThree":"Uncertain","answerFour":"None of the above","userResponse":"","explanationTwo":"False","grade":""}]}

我正在做个人问题:

questionViewModel.startNewGame = function () {


    for (var i = 0; i < questionViewModel.numberOfQuestions - 1; i++) {
        questionViewModel.test.questions[i].userResponse = "";
        questionViewModel.test.questions[i].grade = "";
    }
}

起初它可以工作,但后来我得到的错误无法设置未定义的属性userResponse。

我不知道如何解决这个问题。请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以尝试初始化一个空的问题数组,并像Question对象一样推送每个问题。

questionViewModel.startNewGame = function () {
    questionViewModel.test.questions = [];

    for (var i = 0; i < questionViewModel.numberOfQuestions; i++) {
        questionViewModel.test.questions.push({"userResponse": "", "grade": ""});
    }
}