JavaScript 抛出 "is undefined"错误

标签 javascript jquery

我一直在使用 Javascript,最近遇到了一个无法解决的错误。

Firefox 控制台抛出“info[last]未定义”错误,我不知道是什么原因造成的。这是代码,引起麻烦的行是第 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);
});

希望大家能帮我解答

最佳答案

怎么样:

$("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 来在尝试访问对象的属性之前仔细检查数组中该点是否存在对象。

关于JavaScript 抛出 "is undefined"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3267367/

相关文章:

javascript - 为什么 meteor 会被认为是不安全的?

javascript - 未捕获的 TypeError : Object function (){return i. apply(this,arguments)} 没有方法 'on'

javascript - 使用 JQUERY RAILS 从 Controller 获取参数

php - 在通过 jQuery 上传到数据库之前,如何使用进度条和图像预览上传图像?

jquery - Footable V3 Ajax数据加载: Error: No Columns Supplied

javascript - 弹出框同时打开

javascript - 使用 jQuery 进行几次 ajax 请求后,live()、delegate() 和 on() 停止工作

javascript - 导航到另一个页面时使用 PushState/PopState 保留 div 内容

javascript - 无法清除模态窗口关闭操作上的间隔

javascript - 从另一个模式中启动模式窗口