[英]getJSON variable returns undefined
我不知道為什么getJSON中的'streamName [i]'返回'undefined'。 它里面的所有內容都返回正確的值,但只有streamName返回未定義的值
var streamName = ['LCK1', 'ryan_clark', 'syndicate', 'riotgames', 'esl_csgo', 'Nightblue3', 'summit1g', 'imaqtpie', 'sodapoppin', 'captainsparklez']; var nullLogo = "https://dummyimage.com/50x50/ecf0e7/5c5457.jpg&text=0x3F"; var name; for (var i = 0; i < streamName.length; i++) { var url = 'https://api.twitch.tv/kraken/streams/' + streamName[i] + '?callback=?'; $.getJSON(url, function(data) { console.log(name); if (data.stream == null) { $('.streamersList').append('<div> <div class="logo"> <img src=' + nullLogo + '></div> <div class="nameStreamer">' + streamName[i] + '</div> <div class="state"> Offline </div></div>'); } else { $('.streamersList').append('<div> <div class="logo"> <img src=' + data.stream.channel.logo + '></div> <div class="nameStreamer">' + streamName[i] + '</div> <div class="state">' + data.stream.channel.game + ' </div></div>'); } }); }
因為$.getJSON
是一個異步函數,所以在回調運行時, i
將完成循環。 由於當i
大於或等於streamName
的長度時循環中斷,因此i
將嘗試通過數組末尾( undefined
訪問streamName
的元素。
在這種情況下, i
之所以在每個回調實例內部包含10個原因,是因為作用域在JavaScript中起作用。 據代碼所知, i
與streamName
, nullLogo
和name
一起在函數的頂部聲明。 在循環中進行迭代時, i
的值會更改,並且該更改在函數內部的所有位置(包括尚未運行的回調內部)都可見。 到它們運行時, i
將為10,因為它已到達循環的結尾,這就是回調將使用的值。
確保在$.getJSON
函數中獲得正確的i
值的一種方法是將i
作為參數傳遞給立即調用的函數。 這將有效地將i
的當前值綁定到參數index
,因此基於循環的迭代,使用index
將元素從數組中取出將具有正確的值。
for (var i = 0; i < streamName.length; i++) {
// note how i can be used here because this is synchronous, aka happening right now
var url = 'https://api.twitch.tv/kraken/streams/' + streamName[i] + '?callback=?';
(function(index) {
$.getJSON(url, function(data) {
// this is asynchronous (happens in the future), so i will have a different
// value by the time it is called, but index will have the correct value
console.log(name);
if (data.stream == null) {
$('.streamersList').append('<div> <div class="logo"> <img src='
+ nullLogo
+ '></div> <div class="nameStreamer">'
+ streamName[index]
+ '</div> <div class="state"> Offline </div></div>');
} else {
$('.streamersList').append('<div> <div class="logo"> <img src='
+ data.stream.channel.logo
+ '></div> <div class="nameStreamer">'
+ streamName[index]
+ '</div> <div class="state">'
+ data.stream.channel.game
+ ' </div></div>');
}
});
})(i);
}
$.getJSON
是一個異步函數。 因此,當函數回調發生時,循環已經循環了i的所有迭代。 因此,在您的情況下,我的值是streamName.lenghth
這使streamName[i]
未定義
我會避免在這樣的回調中使用索引。 您需要使用的是立即調用的函數express(IIFE)簽出此其他stackoverflow帖子。 如何在循環期間訪問jquery getJson調用($ .getJson)中的索引變量?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.