Javascript-在数组索引中循环的问题

Javascript - Troubles with looping through array index

本文关键字:循环 问题 索引 数组 Javascript-      更新时间:2023-09-26

我正在做一个测试,显示你答对了多少问题。我已经设法解决了第一个问题,但我很难弄清楚如何循环处理数组中的所有其他问题。

这是我的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]返回"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!!";
}