函数不会't递增给定的变量

The function doesn't increment the given variable

本文关键字:变量 函数      更新时间:2023-09-26

当用户单击按钮时,它将验证是否选中了任何单选按钮(checkChoices()),如果是,它将比较选中的单选按钮的值和correctAnswer

问题出在keepScore()函数上,因为对于任何答案,score都保持为0。

var score = 0;
var checkChoices = function(){
    for (var i = 0; i < choices.length; i++) {
        if (choices[i].checked) {
            var value = choices[i].value;
            choices[i].checked = false;
        }
    }
    return value;
};
//the keepScore function doesn't increment
var keepScore = function(){
    if(checkChoices() == allQuestions[y].correctAnswer) {
        score++;
    }
};
var behavior = function(){
    if(y<allQuestions.length-1 && checkChoices()) {
        keepScore();
        y++;
    }
};
nextBtn.onclick = function(){
    behavior();
};

您需要在函数的开头声明var值。否则,函数将始终返回undefined,因为var至少需要在return语句的范围内。