2015-08-30 64 views
1

https://gist.github.com/IllusionElements/ae5427f9675c276f2195/http://codepen.io/illusionelements/pen/mebZVR代碼的Javascript,抽搐API調用,重複的圖像/ null返回

目前試圖建立一個抽搐API的網站,顯示用戶和他們的數據流。目前我似乎無法弄清楚爲什麼在線/離線部分沒有顯示/正在添加,並且在這部分代碼中,似乎所有內容都返回爲null,但是當我使用console.log時,並非所有內容都會返回爲空。這是代碼:

for (i; i < user.length; i++) { 
     str += "<a href='" + url + "'>" 
     str += "<div class='row border new'>"; 
     str += "<img class='col-md-2' id='profile' src='" + logo + "'>" 
     str += "<p class='col-md-5'>"; 
     str += user[i]; 
     str += "</p>"; 
     if (streamsObj !== null) { //if this doesn't evalute as null run it, strangely enough it's running as if its all null 
      stat.push(streamsObj.channel.status); 
      str += "<span class='col-md-5 circle' id='online'>" 
      str += "</span>" 
      str += "<p class='col-md-12' id='status'>" 
      str += stat[i]; 
      str += "</p>" 
     } else if (streamsObj === null) { //Not being run at all here. It's being skipped// 
      str += "<span class='col-md-5 circle' id='offline'>" 
      str += "</span>" 
      str += "<p class='col-md-12' id='status'>" 
      str += "Ooops" + " " + user[i] + " " + "is Offline, maybe later?" 
      str += "</p>" 

回答

0

你有一個非常複雜的邏輯,但這種情況正在發生,因爲$.ajax函數運行異步http://api.jquery.com/jquery.ajax/。因此,當您前往streamsObj並指定一個值,然後在您的通話中獲得結果時,您可以撥打$.ajax電話,streamsObj中的值會更改。

如果您想保留當前的邏輯,您可以使用streamsObj作爲對象,並具有類似於「關聯數組」的關鍵字將是用戶的用戶名。

所以不是:

var streamsObj = twitch.stream; 

你可以有這樣的:

var streamsObj = {} //a global var outside the function 
streamsObj['the-username'] = twitch.stream; 

另外的邏輯是非常複雜的,現在,你創建的API調用,用戶會希望每次過濾所有,在線,離線。最好只讓用戶使用一次,並使用https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter進行過濾。例如http://codepen.io/biancamihai/pen/XbXqdM