2010-07-16 39 views
0

我一直在使用Javascript,最近我一直困扰着一个我无法解决的错误。Javascript会抛出一个“未定义”错误

Firefox控制台会抛出“info [last] is undefined”错误,我不知道是什么导致了这种情况。这里是代码,引发麻烦的线是7号:

$("textarea").each(function() { 
var id = $(this).parents("div.article").attr('id').split('_')[1], 
    kind = $(this).attr("class"), 
    text = $(this).val(), 
    last = info.length-1; 

    if(last !== 0) { 

     if(info[last].id == id) { 
      info[last].info.push([kind, text]); 

     } 

    } else { 

     object = { 
      id: id, 
      info: [[kind, text]] 
     }; 

    } 

    info.push(object); 
}); 

希望你们可以帮我弄明白。

+0

'info'中发生了什么,其中有零个元素? “信息”在哪里定义? – 2010-07-16 17:27:06

+0

没看过!==以前,你确定它有效吗? (与!=相比) 编辑:R. Hill是对的,如果info有0个元素,那么你做一个info [-1] .id == id ... 更改最后!==检查最后> 0 – Steffen 2010-07-16 17:28:39

+0

Steffen:!==是严格的!=,它不会进行类型转换。 – Jake 2010-07-16 17:36:34

回答

2

如何:

$("textarea").each(function() { 
var id = $(this).parents("div.article").attr('id').split('_')[1], 
    kind = $(this).attr("class"), 
    text = $(this).val(), 
    last = info.length-1; 

    if(last >= 0) { 
     //Check the index exists before accessing it - incase its null or similiar.. 
     //Strictly speaking, we should test for the properties before we access them also. 
     if(info[last]) { 
     if(info[last].id == id) { 
      info[last].info.push([kind, text]); 

     } 
     } 

    } else { 

     object = { 
      id: id, 
      info: [[kind, text]] 
     }; 
     info.push(object); //Also move this up. 

    } 


}); 

我动了几周围的事物,并改变了检验有效的“最后一个”。否则,我还添加了一个if,如果在尝试访问其属性之前检查数组中该点是否存在该对象。

1

如果info为空,则last将为-1

更改if

if(last !== -1) { 

而且,你可能要移动

info.push(object); 

else内。

+0

谢谢,它工作得很好:) – 2010-07-16 17:41:11

+1

然后,你应该通过点击镂空检查来接受这个答案。 – SLaks 2010-07-16 17:43:17

相关问题