我有一個JSON對象,我使用jQuery的parseJSON函數進行解析。我給你孩子一個對象到一個局部變量,然後我遍歷使用for循環如下:Javascript對象獲取未定義的固定長度的循環
var posts = feedObj["posts"];
content+= "<h2 title=\"" + feedDescription + "\"><a href=\"" + feedPermalink + "\">" + feedTitle + "</a></h2>";
content+= "<ul class=\"feedList\">";
for (var i = 0; i < 10; i++) {
console.log(posts[i]["postTitle"]);
var postTitle = posts[i]["postTitle"];
if((typeof posts[i] != "undefined") || postTitle != null) {
content+= "<li>";
console.log("AJ::PostTitle"+postTitle);
content+= "<a href=\"" + decodeURIComponent(posts[i]["permaLink"]) + "\" target=\"_blank\">" + unescapeHTML(postTitle) + "</a>";
content+= "</li>";
}
}
出於某種原因,var postTitle = posts[i]["postTitle"];
總是提供了以下錯誤: Uncaught TypeError: Cannot read property 'postTitle' of undefined
我有不知道爲什麼會發生這種情況。控制檯語句正確輸出postTitle,但分配始終失敗。我究竟做錯了什麼?
如果添加了一個'的console.log(帖[1])會發生什麼拿到第10個職位,更換;'您現有的前日誌聲明?它看起來像'posts'數組中的一個索引是未定義的,您可能會從日誌語句中獲取錯誤。 – Krease
@Chris,這是問題。在for循環條件檢查中將其更改爲posts.length固定它 –