在JS中填充2D数组

时间:2013-09-29 11:03:10

标签: javascript arrays firebase

我正在尝试使用Firebug API填充2D数组,

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] );
      });
    });

但这打破了网站[网站计数器] [0],并表示未定义。有任何线索如何使用它?

2 个答案:

答案 0 :(得分:0)

你有没有尝试过 sites[siteCounter] = [];sites[siteCounter][0]之前?

我假设您必须将其声明为一个数组,以便能够将数据放入数组中。

答案 1 :(得分:0)

如果你想要2D数组,你必须像这样初始化:

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.");