Javascript对象在固定长度的for循环中变得未定义 [英] Javascript object getting undefined in fixed-length for loop

查看:168
本文介绍了Javascript对象在固定长度的for循环中变得未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用jQuery的parseJSON函数解析的JSON对象.我将一个子对象分配给一个局部变量,然后使用for循环对其进行遍历,如下所示:

I have a JSON object that I parse using jQuery's parseJSON function. I assign one of the child objects to a local variable which I then iterate over using a for loop as follows:

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

For some reason, the var postTitle = posts[i]["postTitle"]; always gives the following error: Uncaught TypeError: Cannot read property 'postTitle' of undefined

我不知道为什么会这样. console语句正确打印出postTitle,但是分配始终失败.我在做什么错了?

I have no idea why this is happening. The console statement prints out the postTitle correctly but the assignment always fails. What am I doing wrong?

推荐答案

代替

for (var i = 0; i < 10; i++) {

添加数组对象的检查条件

Add the check condition for the array object

for (var i = 0; i < posts.length ; i++) {

也许您要引用的数组中可能没有10个条目.后一种方法应该可以解决问题.

Maybe the array you are referring to might not have 10 entries in it. The later approach should solve the problem..

这篇关于Javascript对象在固定长度的for循环中变得未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆