我想從api獲取數據,但是我正在使用的For循環在嵌套的GetJSON調用中返回具有null和未定義值的對象,但是當我嘗試forEach循環時工作正常。 任何想法爲什麼?For循環和ForEach循環展現與getJSON不同的行爲
var baseUrl = "https://wind-bow.gomix.me/twitch-api/";
var channels = ["ESL_SC2", "FreeCodeCamp", "Test_channel", "brunofin"];
//**First function with forEach. WORKS FINE**
function getDataForEach() {
channels.forEach(function(channel) {
$.getJSON(txtUrl('streams', channel), function(json) {
console.log(json);
$.getJSON(txtUrl('channels', channel), function(json2) {
console.log(json2);
});
});
});
}
//**Second function with a normal for loop. The 2nd JSON doesnt return the proper data**
function getDataForLoop() {
for (i=0;i<channels.length;i++){
$.getJSON(txtUrl('streams', channels[i]), function(json) {
console.log(json);
//THIS 2nd call doesnt returns undefined objects.
$.getJSON(txtUrl('channels', channels[i]), function(json2) {
console.log(json2);
});
});
});
}
function txtUrl(prop, chnl) {
return baseUrl + prop + '/' + chnl + '?callback=?';
}
$(document).ready(function() {
getData();
});
你試過把一個斷點在你的第二個電話,並檢查'i'的價值? – litelite
是的。現在我明白爲什麼它不起作用。 –