javascript - 无法获取未定义的属性 "userResponse"

标签 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 的错误。

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

最佳答案

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

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

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

关于javascript - 无法获取未定义的属性 "userResponse",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40348647/

相关文章:

javascript - 根据对象数组中的重复值将对象分组

javascript - 将新的 FormGroup 插入 FormArray 将动态 FormGroup 标记为无效

c# - 编译器不会让我使用三元运算符返回对象

php - 如何刷新正在执行php代码的div

javascript - 合并 JS 文件(JSONish)

json - 如何快速从本地JSON文件中获取数据?

c# - POST 方法的参数始终为 null

python - python对象什么时候创建的?

php - 将 PHP 数组作为数组传递给外部 Javascript 函数

javascript - 在 html 网页加载时显示 JavaScript 表