我一直在使用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 :(得分: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.
}
});
我已经移动了一些东西,并更改了有效'last'的检查。否则我还在尝试访问它的属性之前添加了一个if来仔细检查数组中该对象是否存在。
答案 1 :(得分:1)
如果info
为空,则last
将为-1
。
将if
更改为
if(last !== -1) {
此外,您可能想要移动
info.push(object);
在else
内。