I've been working with Javascript and recently I've been stucked with an error which I can't solve.
The Firefox console throws an "info[last] is undefined" error, and I've got no idea what is causing that. Here is the code, the line which provokes the trouble is number 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);
});
Hope you guys can help me figure it out.
How about:
$("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.
}
});
I've moved a few things around, and changed the check for valid 'last'. Otherwise I've also added an if to double check that an object exists at that point in the array before trying to access it's properties.
If info
is empty, last
will be -1
.
Change your if
to
if(last !== -1) {
Also, you probably want to move
info.push(object);
inside the else
.
精彩评论