2017-08-24 64 views
1

我想從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(); 
}); 
+1

你試過把一個斷點在你的第二個電話,並檢查'i'的價值? – litelite

+0

是的。現在我明白爲什麼它不起作用。 –

回答

3

getJSON是異步的,所以它的回調函數不會馬上執行,從而在for環的情況下,如果你使用i回調中會產生this error

我注意到的另一件事是您使用全球i這也是source of troubles

如果you'are使用ECMAScript 6可以使用let聲明i

for(let i = 0; ...) 

let是塊作用域所以使用它不會產生上文所述第一鏈路的誤差。

+0

謝謝你。我不知道Javascript中隱含的全局事物。 –