如何在javascript中遍历列表

时间:2017-10-06 10:52:52

标签: javascript jquery

服务器返回一个数据列表,我想迭代列表。

以下是数据的结构(从浏览器调试器获取):

enter image description here

功能:

function (token) {
    hub.server.getOnlinePlayers(token).done(function (onlinePlayers) {
        MyData.nextOnlinePlayersToken = onlinePlayers.Token;
        $.each(onlinePlayers.Items, function () {
            var id = this.userId;
        });
    });
}

直到这一行一切正常(Token值故意为空):

MyData.nextOnlinePlayersToken = onlinePlayers.Token;

但调试器的下一行显示onlinePlayers未定义。什么可能是错的?感谢。

1 个答案:

答案 0 :(得分:2)

我认为你错了$.each()$(selector).each()

$( "li" ).each(function( index ) {
  // here you can access current li element with this.
});

您正在尝试获取调用每个对象的jQuery对象,但您没有它。我相信在这种情况下this是全局jQuery对象。

如果使用$.each()

,则需要传递索引和值参数
$.each(onlinePlayers.Items, function (index, value) {
   var id = value.userId; 
});