我使用Google接收书籍列表,但有时一些图书条目没有一些键/属性,例如Authors,或者没有缩略图。因此,JavaScript说,我试图访问的属性是未定义的,我的应用程序会停止工作。
全链路
https://www.googleapis.com/books/v1/volumes?q=java&callback=jQuery191020691258599981666_1377508821982&_=1377508821983例如,当作者失踪时
TypeError: row.volumeInfo.authors is undefined我试着提出两种解决方案
if ( typeof (authors) != "undefined"){}和
if('authors' in booksObject) {}但它们似乎都不起作用,因为它们从来不进入循环,即使在这个早熟存在的时候也是如此。
这就是我打电话的地方
function populateListview(books) {
//iterate each returned item
$.each(books.items, function(i, row) {
//populate each row in the list
var htmlString = '<li><a href="book_details.html?id=' + row.id + '"><img src="';
htmlString += row.volumeInfo.imageLinks.thumbnail + '"';
htmlString += 'class="ui-li-has-thumb"/><h3>';
//Check if authors exists in JSON
htmlString += row.volumeInfo.title + '</h3><p>' + row.volumeInfo.authors[0] + '</p></a></li>';
//If not add an undefined authors string in the authors
console.log(htmlString);
//append new html to the list
$('#book_list').append(htmlString);
});
$('#book_list').listview('refresh');
// refresh the list-view so new elements are added to the DOM
};发布于 2013-08-26 09:10:40
您可以检查$.isArray(row.volumeInfo.authors) && row.volumeInfo.authors.length > 0
console.log(books.toString());
// iterate each returned item
$.each(books.items, function(i, row) {
// populate each row in the list
var htmlString = '<li><a href="book_details.html?id=' + row.id
+ '"><img src="';
htmlString += row.volumeInfo.imageLinks.thumbnail + '"';
htmlString += 'class="ui-li-has-thumb"/><h3>';
if ($.isArray(row.volumeInfo.authors) && row.volumeInfo.authors.length > 0) {
// code for what to do with json here
htmlString += row.volumeInfo.title + '</h3><p>'
+ row.volumeInfo.authors[0] + '</p></a></li>';
} else {
htmlString += row.volumeInfo.title + '</h3><p>' + "Author Undifined"
+ '</p></a></li>';
}
console.log(htmlString);
// append new html to the list
$('#book_list').append(htmlString);
});
$('#book_list').listview('refresh');
// refresh the list-view so new elements are added to the DOM发布于 2013-08-26 09:19:25
试试这个:
if(booksObject.image) {
//do stuff with it
} else if( booksObject.author ) {
//do stuff with author
}发布于 2014-06-11 13:49:24
这里有一种非常简单的方法来检查JSON中是否存在任何键或值。
var jsonString = JSON.stringify(yourJSON);
if (jsonString .indexOf("yourKeyOrValue") > -1){
console.log("your key or value exists!");
}它是快速,简单,容易。
https://stackoverflow.com/questions/18440522
复制相似问题