json Uncaught TypeError错误:无法读取属性'选择'的未定义

Error with json Uncaught TypeError: Cannot read property 'choices' of undefined

本文关键字:选择 未定义 属性 读取 TypeError Uncaught 错误 json      更新时间:2023-09-26

choices是json对象中的一个嵌套数组,我将这些数据放在一个多选测试序列中。当我按下该函数的触发器时,控制台显示"未捕获类型错误:无法读取未定义的"的属性"选项"。"我还有一个变量"c",当用户选择另一个检查时,该变量会发生变化,因此语句exact=exact+c将使放置函数起作用。"。

var exam0 = [
    {
        "question": "which is a negative number?",
        "choices": [
            "2",
            "-2",``
            "6",
            "8",
        ],
        "correctAnswer": "B",
        "hint": "The one with the ' - ' negative sign"
    },
    ......other questions****
 
];

功能是

function placement(x) /*x is variable used to change the question from the json object*/
{
    choiceOne=$('<p>').text('A.'+exam[x].choices[0]); /*where the console points to problem*/
    choiceTwo=$('<p>').text('B.'+exam[x].choices[1]);
    choiceThree=$('<p>').text('C.'+exam[x].choices[2]);
    choiceFour=$('<p>').text('D.'+exam[x].choices[3]);
    currentQuestion=$('<p>').text(exam[x].question);
    $("#honeyPot").empty().append(currentQuestion);
    $("#honeyPot p").prepend(count+".");
    $('#options').find('p').remove().hide();
    $('#optionOne').fadeIn(250).append(choiceOne);
    $('#optionTwo').fadeIn(250).append(choiceTwo);      
    $('#optionThree').fadeIn(250).append(choiceThree);
    $('#optionFour').fadeIn(250).append(choiceFour);    
}

我认为您也应该在函数中使用exam0而不是exam,因为exam0是json对象。

function placement(x) /*x is variable used to change the question from the json object*/
{
    choiceOne=$('<p>').text('A.'+exam0[x].choices[0]); /*where the console points to problem*/
    choiceTwo=$('<p>').text('B.'+exam0[x].choices[1]);
    choiceThree=$('<p>').text('C.'+exam0[x].choices[2]);
    choiceFour=$('<p>').text('D.'+exam0[x].choices[3]);
    currentQuestion=$('<p>').text(exam0[x].question);
    $("#honeyPot").empty().append(currentQuestion);
    $("#honeyPot p").prepend(count+".");
    $('#options').find('p').remove().hide();
    $('#optionOne').fadeIn(250).append(choiceOne);
    $('#optionTwo').fadeIn(250).append(choiceTwo);      
    $('#optionThree').fadeIn(250).append(choiceThree);
    $('#optionFour').fadeIn(250).append(choiceFour);    
}