Javascript: variable TypeError undefined

I am currently creating a small web application with similar functionality in all modules. I want to encode small general functions so that all programmers next to me call these functions, and these functions return the necessary but important data for their implementation. In this example, I am trying to figure out a typical exercise, "choose true or false." Therefore, from template.php, they call this function:

function checkAnswers(){
var radiobuttons = document.form1.exer1;
var correctAnswers = answers(); //this is an array of string
var checkedAnswers = checkExerciseRB(radiobuttons, 2, correctAnswers);
    for(i=0; i<checkedAnswers.length; i++){
        alert(checkedAnswers[i]);
    }
}

The checkExerciseRB function is my general function, it is called from verification.

function checkExerciseRB(rbuttons, opciones, correct){
    var answers = new Array();
    var control = 0;
    for(i=0; i<rbuttons.length; i++){
        var noPick="true";
        for(j=0; j<opciones; j++){
            if(rbuttons[control+j].checked){
                if(rbuttons[control+j].value==correct[i]){
                    answers[i]= 1;
                    noPick="false";
                    break;
                }
                else{
                    answers[i]=2;
                    noPick="false";
                    break;
                }
            }
        }
        if(noPick=="true")
            answers[i]=0;
        control=control+opciones;
    }
    return answers;
}

It works fine, but looking at the error log of my favorite browser (FireFox, Chrome), it says:

TypeError: rbuttons[control + j] is undefined

Any clue on how to deal with this issue?

+5
source share
3 answers

, , , control + j rbuttons. , rbuttons[control + j].

JavaScript ! . , , , , , , control .

, : ", !"

+6

rbuttons.length , 2 control. control, , .

+1

, + j? i.e: 4, 5 ?

In addition, you should use var i, var j, etc. inside the for loop. Without this, your variables leak into the area in which this code is executed (most likely, the global area, and this is not good) :)

0
source

All Articles