当有值分配给它时,数组对象返回空 - Javascript

The array object returned empty when there are values assigned to it - Javascript

在使用 tumblr 构建项目时 API、

var latest = [];
client.posts('XXXXXX', function (err, blog) {
    for (var i = 0; i <

    blog.posts.length; i++) {
        var post = blog.posts[i];
        // this condition is used to identify if any blog post is dated no later than 7 days. 
        if ((new Date().valueOf() - Date.parse(post.date)) /(1000*60*60*24) <= 7){   latest.push(post); 
/ / console.log(post);
        }
    };
});

console.log(latest)

latest 是一个变量,存储任何满足条件的博客 post 对象。取消注释 console.log(post) 时,命令行打印 post 对象,如下所示:

{ blog_name: '......',
  id: ......,
  post_url: '......',
  slug: '......',
  type: 'text',
  date: '2015-07-20 16:42:30 GMT',
  timestamp: ....,
  state: 'published',
  format: 'html',
  reblog_key: '.....',
  tags: [],
  short_url: '.......',
  recommended_source: null,
  followed: false,
  highlighted: [],
  liked: false,
  note_count: 0,
  title: '.....',
  body:.......}

但是,对于 console.log(最新),命令行会打印 []。为什么 latest 在这里返回一个空数组?

正如评论中指出的那样,client.posts() 是一种异步方法,因此它不会像您期望的那样按顺序工作。

var latest = [];
client.posts('XXXXXX', function (err, blog) {
    // This is not reached until AFTER you hear back from the API
    // and latest has already been logged.
});

console.log(latest)

如果您想等到收到 API 的回复后再打印,您将需要使用一些异步编程方法,例如 promises 或在client.posts回调。

这将正确打印:

var latest = [];
client.posts('XXXXXX', function (err, blog) {
    for (var i = 0; i < blog.posts.length; i++) {
        var post = blog.posts[i];
        if ((new Date().valueOf() - Date.parse(post.date)) /(1000*60*60*24) <= 7){
            latest.push(post);
        }
    }
    console.log(latest); // Prints when for loop completes
});