Javascript:TypeError 变量未定义 [英] Javascript: TypeError variable is undefined

查看:38
本文介绍了Javascript:TypeError 变量未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个在所有模块中具有类似功能的小型 Web 应用程序.我想编写小的通用函数,以便我身边的所有程序员调用这些函数,这些函数返回必要但重要的数据,以便他们实现其功能.在这个例子中,我试图处理典型的选择真或假"练习.所以从 template.php 他们调用这个函数:

I am currently building a small web application with similar functionality across all modules. I want to code small generic functions so that all programmers next to me, call these functions and these functions return necessary but important data for them to implement their functionality. In this example, I am trying to deal with the typical "choose true or false" exercise. So from the 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]);
    }
}

函数 checkExerciseRB 是我的通用函数,它是从 checkAnswers 调用的.

Function checkExerciseRB is my generic function, it is called from checkAnswers.

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;
}

效果很好,但在查看我最喜欢的浏览器(FireFox、Chrome)错误日志时,它说:

It works great but while looking at my favorite browsers (FireFox, Chrome) error log it says:

TypeError: rbuttons[control + j] is undefined

关于如何处理这件事的任何线索?

Any clue on how to deal with this matter?

推荐答案

这大概是说control + j 大于等于数组rbuttons的长度.没有像 rbuttons[control + j] 这样的数组元素.

This probably means that control + j is greater than or equal to the length of the array rbuttons. There's no such array element as rbuttons[control + j].

您应该学习如何在您喜欢的浏览器中使用 JavaScript 调试器!调试器很棒.它们让您可以随心所欲地一行一行地观察这段代码的运行速度,并观察 control 的值如何随您的运行而变化.

You should learn how to use the JavaScript debugger in your favorite browsers! Debuggers are great. They let you watch this code run, line by line, as fast or as slow as you want, and watch how the value of control changes as you go.

你会看着它,你会想哦!那行代码是错误的!"

You’ll watch it, and you’ll think "Oh! That line of code is wrong!"

这篇关于Javascript:TypeError 变量未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆