2017-10-06 53 views
0

服务器返回一个数据列表,我想遍历列表。如何遍历javascript中的列表

下面是数据是如何构成的(从浏览器调试得到了它):

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值为null故意):

MyData.nextOnlinePlayersToken = onlinePlayers.Token; 

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

回答

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; 
}); 
+0

在我的代码我有一个错字。 'this.userId'应该是'this.UserId' ..现在它工作正常..谢谢反正 – Blendester