2013-09-29 154 views
0

我想popoulate使用Firebug API一個二維數組,填充二維數組在JS

var sites = []; 
    var siteCounter = 0; 

    //Firebase API Calls 

    var messageListRef = new Firebase('https://my.firebaseio.com'); 
    messageListRef.once('value', function(allMessagesSnapshot) { 
     allMessagesSnapshot.forEach(function(messageSnapshot) { 
     var latitude = messageSnapshot.child('latitude').val(); 
     var longitude = messageSnapshot.child('longitude').val(); 
     sites[siteCounter][0] = 'siteCounter'; 
     sites[siteCounter][1] = latitude; 
     sites[siteCounter][2] = longitude; 
     sites[siteCounter][3] = siteCounter; 
     sites[siteCounter][4] = 'This is siteCounter.'; 

     siteCounter++; 
     alert(sites[siteCounter][1] + " " + sites[siteCounter][2]); 
     }); 
    }); 

但是,這打破了網站[siteCounter] [0],並說,這是不確定的。任何線索如何使用這個?

回答

0

如果你想二維數組,你必須初始化這樣的:

var tab = new Array(); 

tab[0] = new Array(); 

試試這個代碼

sites[siteCounter] = new Array(); 
sites[siteCounter][0] = 'siteCounter'; 
sites[siteCounter][1] = latitude; 
sites[siteCounter][2] = longitude; 
sites[siteCounter][3] = siteCounter; 
sites[siteCounter][4] = 'This is siteCounter.'; 

或直接

sites[siteCounter] = new Array("siteCounter", latitude, longitude, siteCounter, "This is siteCounter."); 
+0

問題是我失去了foreach循環之外的所有值 – CodeMonkey

+0

你確定嗎?因爲在這個例子中,我寫了jsFiddle,我不會失去我的價值http://jsfiddle.net/UdD2L/ –

0

您是否嘗試過 sites[siteCounter] = []; 之前sites[siteCounter][0]

我假設你必須將它聲明爲一個數組才能夠將數組放入數組中。