繁体   English   中英

在每个函数中循环遍历jQuery数组

[英]Loop through jQuery array in each function not working

我有从另一个函数的API获取的数据。 为了获得数据,我这样做:

var posts = get_posts();

然后,我可以打印到控制台:

console.info( posts );

我将得到这样的结果:

[]
  0: {id: 123, date: "2018-01-01T12:00:00", slug: "asdf-xyz", author: 1, media: 1, …}
  1: {id: 123, date: "2018-01-01T12:00:00", slug: "asdf-xyz", author: 1, media: 1, …}
  ...

该数组中有多个条目,包含各种数据位。

但是,如果我随后尝试遍历它们并执行某些操作,则每个语句都不会执行任何操作。 好像它被完全忽略了(可能是)。

$.each( posts, function( index, record ) {

    alert( index );

});

我在这里做错了什么?

编辑

这是我在一个函数中的代码,该函数返回(或应该)返回数组。 使用简单的console.log返回数据,但是使用stringify仅返回[]

$.each( object, function( key, value ) {

    var post = {
        id: value.id,
        ...
    };

    posts.push( post );

});

console.log( posts ); // prints the data out

JavaScript不是我最强大的编码语言,所以我假设可能是错误地设置了数据?

应该没关系。 我为您整理了一个工作示例。 您能在下面发现您的代码和工作片段之间的区别吗?

 var posts = [ { name: 'Post1' }, { name: 'Post2' } ]; $.each(posts, function(index, record) { console.log(index, record); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

问题可能出在您用来填充数组的代码中。 您能否提供更多背景信息?

您可以使用以下命令打印所有对象:

$.each( posts, function( index, record ) { alert(  JSON.stringify(record) ) });

或使用

$.each( posts, function( index, record ) { alert(  record["slug"] ) });

运行代码并查看演示

 $(function(){ var posts = []; posts.push({id: 123, date: "2018-01-01T12:00:00", slug: "asdf-xyz", author: 1, media: 1}); posts.push({id: 123, date: "2018-01-01T12:00:00", slug: "asdf-xyz", author: 1, media: 1}); $.each( posts, function( index, record ) { alert( JSON.stringify(record) ) }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM