得到此错误:“未捕获的TypeError:无法读取未定义的属性'0'”

时间:2016-02-10 17:08:41

标签: javascript jquery

我在下面的脚本中在Chrome控制台中收到此错误。具体来说,它看起来在第12行有问题。如果有人有解决方案来修复它,将非常感激。提前致谢! P.S:请在这里查看HTML:https://jsbin.com/jojufiqibu/edit?html,js,output

function countChecked() {
  var NUM_QUESTIONS = 26;

  var count = 0; //tracks the number of checked off radio groups
  var total = 0; //tracks the number of correct answers

  //insert a null at Array[0] so tune number matches index number
  correctTunes = new Array(0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0);

  //start at 1 so tune number matches index number
  for (var i = 1; i <= NUM_QUESTIONS; i++) {
   var isYesChecked = eval("document.forms[0].correct"+i+"[0].checked");
   var isNoChecked = eval("document.forms[0].correct"+i+"[1].checked");

   //as long as one of these values is true, the group is checked
   if (isYesChecked || isNoChecked) {
    count++;
   }

   //if isYesChecked matches the corresponding array value, the answer is correct
   if (correctTunes[i] == isYesChecked) {
    total++;
   }
  }

  //if count doesn't match, at least one group isn't checked;
  //must use NaN and not "false" since 0 is a valid returnable number
  if (count < NUM_QUESTIONS) {
   return NaN;
  }

  //returns the number of correct answers, which also doubles as "return true"
  return total;
 }

1 个答案:

答案 0 :(得分:0)

编辑:刚看到你在评论中发布了你的html - 你的html没有任何form元素,因此document.forms[0]将是未定义的。

通常,当您尝试使用类似数组的方括号语法访问值为“Uncaught TypeError: Cannot read property '0' of undefined”的变量时,会出现错误undefined

下面的代码以相当复杂的方式演示了这一点(使用参数设置函数,只调用函数而不传递参数,使该参数undefined。观察控制台是否有错误)

&#13;
&#13;
function doSomething(myArray){
   console.log(myArray[0]); 
}

doSomething();
&#13;
&#13;
&#13;

现在,在您的代码中,这实际上只归结为1件事,document.formsundefined或者循环document.forms[0].correctX的其中一个迭代未定义(其中{{1}是你的循环中的一个值。)

如果没有看到您的HTML,就无法确定究竟发生了什么,但您可以通过逐步调试来调试它,直到发生错误并查看X的值。

顺便说一下,在评论i中已经提到这里是不必要的,你可以使用方括号表示法动态访问对象,这也可以帮助你调试:

eval