2012-04-11 42 views
0

我的目標是遍歷結果數組,並與數據做東西,但由於某種原因,我不能讓JavaScript的foreach循環工作,我似乎無法做任何形式的枚舉工作。JavaScript forEach不工作

這裏是我的測試

console.debug("I got this far."); 
for(var i=0;i< results.length; i++){ 
    console.debug("Worked."); 
} 
console.debug("Past."); 
console.debug(results); 

我也曾嘗試

results.forEach(function(x) { console.debug("Worked"); }); 

for(var x in results) 

似乎都不奏效,是不是我做錯了嗎?

對於上面的輸出是

I got this far. query.html:39 
Past.   query.html:40 
[ Object , Object , Object , Object , Object , Object , Object , Object , Object , Object ] 

所以我知道結果的變量是正確的類型,但它只是不迭代。還有另一個地方forEach()工作正常,但這不是,有關如何調試和解決這個問題的任何建議將是有益的。

全碼(工作液)

var table; 
var request = { query : { match_all : {}}}; 
var map; 
function initialize(results) { 
    var myOptions = { 
     zoom: 8, 
     center: new google.maps.LatLng(41.4, -71.3), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    map = new google.maps.Map(document.getElementById('map_canvas'), 
     myOptions); 
    results.forEach(function(x) { 
     var markerLoc = new google.maps.LatLng(x.location.lat, x.location.lon); 
     var marker = new google.maps.Marker({ 
     position: markerLoc, 
     map: map, 
     title: "Hello World!" 
     }); 
     }); 

}; 
$(document).ready(function() { 
     var results = []; 
     $.ajax({ 
      url: "http://localhost:9200/devices/devices/_search", 
      type: "POST", 
      data: JSON.stringify(request), 
      dataType: "json", 
      beforeSend: function(x) { 
       if (x && x.overrideMimeType) { 
        x.overrideMimeType("application/j-son;charset=UTF-8"); 

        } 
      }, 
      success: function(data) { 
       data.hits.hits.forEach(function(x) { results.push(x._source); }); 
       initialize(results); 
      } 

     }); 

}); 
+4

什麼是結果? 'results.length'有什麼價值?它是如何填充的? – Quentin 2012-04-11 15:15:55

+1

只是想知道'我得到了這個'在39行,'Past.'在40行。 – taskinoor 2012-04-11 15:17:26

+0

@Quentin:看起來像'var results = Object.create(Array.prototype);' – jAndy 2012-04-11 15:18:44

回答

1

您儘快傳遞給results作爲initialize Ajax請求已發送。您不會等待回覆,因此填充它的代碼不會觸發,直到太晚。

將呼叫轉移到initialize,使其位於success處理程序中。

+0

你先生是我今天的英雄。 – lukecampbell 2012-04-11 15:26:50