My code has two functions that pass arrays to another function. The first time I execute this, it works, the second time it doesn't.
First time (snippet of a larger function):
for (m = 0; m < totalAnimals; m++) {
ids = mergedIDs[m];
file = "data/" + ids + ".geojson";
coords = arrayArray[3 * m];
time = arrayArray[3 * m + 1];
props = arrayArray[3 * m + 2];
$.getJSON(file).done(function (data) {
$(data).each(function () {
coords.push(data.geometry.coordinates);
time.push(data.properties.time);
id = data.properties.id;
species = data.properties.species;
sex = data.properties.sex;
props.push(id, species, sex);
});
}).done(function () {
makeTrack(coords, time, props);
coords = []; // clearing in between rounds
time = [];
props = [];
}).fail(function () {
console.log(ids + "multipointCoords not populated");
});
}
The code above successfully passes the three arrays (coords, time, props) to the makeTrack function:
function makeTrack(multipointCoords, tracksTime, properties) {
// parse properties array to assign to features
var id = properties[0],
species = properties[1],
sex = properties[2];
// setup OpenLayers structure and style assignment
var trackSource = new ol.source.Vector(); // create an empty source instance
var lineString = new ol.geom.LineString([ // create a linestring geometry from the GeoJSON data for the tracks
ol.proj.fromLonLat(multipointCoords[0][0])
]);
var icon = new ol.geom.Point( // create a point geometry from the GeoJSON data for the header icons
ol.proj.fromLonLat(multipointCoords[0][0])
);
etc. Everything is great so far. Later in that function I call
segmentConstruction(multipointCoords);
and then
function segmentConstruction(multipointCoords) {
length = multipointCoords[0].length;
if (i < length) {
var timer;
prevCoord = ol.proj.fromLonLat(multipointCoords[0][i - 1]);
currCoord = ol.proj.fromLonLat(multipointCoords[0][i]);
...
I am getting the error:
TypeError: multipointCoords[0] is undefined
I did read this Javascript passing array as parameter to function, but I do not understand the difference between passing references and passing values.
According to Passing an array as parameter in JavaScript, arrays can be passed.
EDIT the arrays are two-dimensional because they are arrays of [lon,lat].
let, the problem would likely go away, however that's not supported by all browsers.coordsvariable, and passes the value of it to the next function, which is a reference to an array that was defined in the last iteration of the for loop. Then, each time .done callback gets called, for each iteration, they're acting upon the same array, the one created in the last iteration. This would surely cause unexpected results, possibly even the error you've come across.