Javascript - 遍历数组索引时出现问题

Javascript - Troubles with looping through array index

我正在做一个测验,显示你答对了多少题。我已经设法让它与第一个问题一起工作,但我正在努力弄清楚如何循环遍历数组中的所有其他问题。

这是我的 JS 代码:

var questionArray = new Array (8);
questionArray [0] = "q1"
questionArray [1] = "q2"
questionArray [2] = "q3"
questionArray [3] = "q4"
questionArray [4] = "q5"
questionArray [5] = "q6"
questionArray [6] = "q7"
questionArray [7] = "q8"



var correctAnswers = 0;

function checkQuestions()
{
    var questions = document.getElementsByName(questionArray[0]);
    var numberOfRadios = questions.length;

    for( var i = 0; i < numberOfRadios; i++)
    {
        if(questions[i].checked)
        {
            if(questions[i].value == "correct")
            {
                correctAnswers++
            }
        }       
    }   
document.getElementById("correctAnswers").innerHTML = "You got:" + "<br>" + correctAnswers + "/8!!";
}

questionArray[0] returns "q1".

如果您只有一个该名称的元素,则 questions.length 将等于 1。

因此,您的 for 循环只会迭代一次。

你想做的,是这样的:

function checkQuestions()
{
    for( var i = 0; i < questionArray.length; i++)
    {
        //I assume you have only one question per name, if not then you need id
        var question = document.getElementsByName(questionArray[i])[0];
        if(question.checked)
        {
            if(question.value == "correct")
            {
                correctAnswers++;
            }
        }       
    }   
    document.getElementById("correctAnswers").innerHTML = "You got:" + "<br>" + correctAnswers + "/8!!";
}

循环遍历问题..

function checkQuestions()
{
    for (var j = 0; j < questionArray.length; j++)
       var questions = document.getElementsByName(questionArray[j]);
       ...
    }

 document.getElementById("correctAnswers").innerHTML = "You got:" + "<br>" + correctAnswers + "/8!!";
}