2017-10-06 51 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