2012-10-17 44 views
0

我試圖在var上存儲我的朋友列表(姓名,圖片和性別),但它無法正常工作。請準備好代碼中的註釋以獲取詳細信息。有任何想法嗎?謝謝。Javascript「push」into array not working(Facebook應用程序)

function getFriendsArray() {  
    var friendsArray = []; 
     FB.api('/me/friends?fields=name,picture,gender', function(response) { 
     if(response.data) { 
     var data = ''; 
     $.each(response.data, function(indice, item) { 
      alert(item.name); // Friend's name are displayed correctly 
      friendsArray.push(item); // I believe this doesn't work 
     });      
     } 
     else { 
      errorHandler('getFriendsArray', JSON.stringify(response)); 
     } 
    }); 

alert(friendsArray.length); // Returns 0 (incorrect) 

return friendsArray.sort(sortByName); 
} 

回答

1

呼叫function(response)是異步的。您應該在$.each

之後插入警報以完整性:您應該將您的方法更改爲問題:不要調用返回數組但返回第二個函數的函數。

function getFriendsArray(callback, errorHandler) {  
    var friendsArray = []; 
     FB.api('/me/friends?fields=name,picture,gender', function(response) { 
     if(response.data) { 
     var data = ''; 
     $.each(response.data, function(indice, item) { 
      alert(item.name); // Friend's name are displayed correctly 
      friendsArray.push(item); // I believe this doesn't work 
     }); 
     callback(friendsArray);      
     } 
     else { 
      errorHandler('getFriendsArray', JSON.stringify(response)); 
     } 
    }); 
} 

getFriendsArray(function(friends) { 
    alert(friends); 
}, 
function(error) { 
    alert('error'); 
}); 
+0

謝謝。第一個警報正在工作(顯然),但第二個警告(在$ .each之後)不是。真正的問題是我返回一個空數組。 – Arturo

+1

第二個不能工作。你應該調用第二個函數來繼續你的算法 –

1

它看起來像FB.api使異步請求(如jQuery.ajax)等你的FB.api調用完成,並推動成果轉化的朋友陣列之前執行alert(friendsArray.length)

+0

謝謝。那麼我能做些什麼來返回具有正確值的數組?讓它同步?謝謝 – Arturo