Javascript抛出一个;是未定义的“;错误

Javascript抛出一个;是未定义的“;错误,javascript,jquery,Javascript,Jquery,我一直在使用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 = $

我一直在使用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);
});

希望你们能帮我弄明白。

如果
info
是空的,
last
将是
-1

将您的
如果
更改为

if(last !== -1) {
而且,你可能想搬家

info.push(object);

else

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

将您的
如果
更改为

if(last !== -1) {
而且,你可能想搬家

info.push(object);
else

中,如何:

$("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.

    }


});
我移动了一些东西,并更改了有效“last”的检查。否则,我还添加了一个if,以便在尝试访问对象的属性之前仔细检查数组中该点是否存在对象。

如何:

$("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.

    }


});

我移动了一些东西,并更改了有效“last”的检查。否则,我还添加了一个if,以在尝试访问对象的属性之前,再次检查数组中该点是否存在对象。

在“info”中发生的事情中是否包含零元素?“信息”在哪里定义?尚未看到!==之前,你确定它有效吗?(与!=)编辑:R.Hill是对的,如果info有0个元素,则执行info[-1]。id==id。。。更改最后一个!==检查到最后一个>0Steffen:!==是严格的!=,它不进行类型转换。在“info”中发生的事情中没有任何元素?“信息”在哪里定义?尚未看到!==之前,你确定它有效吗?(与!=)编辑:R.Hill是对的,如果info有0个元素,则执行info[-1]。id==id。。。更改最后一个!==检查到最后一个>0Steffen:!==是严格的!=,它不进行类型转换。然后,您应该通过单击空心检查来接受此答案。然后,您应该通过单击空心检查来接受此答案。