Javascript Array Problem

I am trying to populate an array with values from other arrays:

var longitude = responseDoc.getElementsByTagName(“lonDD”);
var latitude = responseDoc.getElementsByTagName(“latDD”);
var trackDate = responseDoc.getElementsByTagName(“trackDate”);

these are all good and have 10 values each. I then define an array:

var pointsArray=new Array(10, 10);

then populate the array:

for(i=0; i<longitude.length; i++){

  for (j=0; j &lt;3; j++){

	pointsArray[i][j]=longitude[i].firstChild.nodeValue;
	pointsArray[i][j]=latitude[i].firstChild.nodeValue;
	pointsArray[i][j]=trackDate[i].firstChild.nodeValue;
  
  }

}

This bangs me out when it gets to the third set of values:

pointsArray[i] is undefined

These are the values I’m working with

-2.7532501000, 52.5777060000, 2011-03-26 12:18:04

var pointsArray = [ [“A1”,“A2”,“A3”],…[“I1”,“I2”,“I3”],[“J1”,“J2”,“J3”] ];

You are attempting to create a multi-dimensional array using what you know of from other programming languages. That doesn’t work here.

When new Array is given one term, that’s the array length that will be created. You aren’t limited to that length either.
When multiple terms are given, you are defining those individual terms as the array itself.
See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

To create a multidimensional array, there is no native initializer for that. You have to place an array instead of an item, instead.
The other problem is that the inner loop is replacing the j item, so only the last item would remain.

So, here’s the simple way to create a multi-dimensional array:


var pointsArray = [];
for (i = 0; i < longitude.length; i++) {
    pointsArray[i] = [];
    pointsArray[i][0]=longitude[i].firstChild.nodeValue;
    pointsArray[i][1]=latitude[i].firstChild.nodeValue;
    pointsArray[i][2]=trackDate[i].firstChild.nodeValue;
}

And here’s another way that I prefer to do it:


var pointsArray = [];
for (i = 0; i < longitude.length; i++) {
    pointsArray[i] = [
        longitude[i].firstChild.nodeValue,
        latitude[i].firstChild.nodeValue,
        trackDate[i].firstChild.nodeValue
    ];
}

But why don’t you use object notation instead?


var pointsArray = [];
for (i = 0; i < longitude.length; i++) {
    pointsArray[i] = {
        long: longitude[i].firstChild.nodeValue,
        lat: latitude[i].firstChild.nodeValue,
        date: trackDate[i].firstChild.nodeValue
    };
}

That way you can reference a value using pointsArray[3].long and your code can become that much more understandable.

Which in practice you would swiftly have altered to:


var pointsArray = [];
for (i = 0; i < longitude.length; i++) {
    pointsArray[i] = [B]{[/B]
        long: longitude[i].firstChild.nodeValue,
        lat: latitude[i].firstChild.nodeValue,
        date: trackDate[i].firstChild.nodeValue
   [B]}[/B];
}

Yes, that wasn’t caught when reworking from one version to the next. Updating the original now.