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 <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:
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.