Reputation: 183
I generate some javascript from a php file. In this generated code, I create a multi-dimensional array and then populate it. The first nested array populates without problems but the second ones throws a TypeError: myArray[idx] is undefined.
Here's a code snippet:
function initialize() {
var arrayLabels = [];
var arrayMarkers = [];
var idx = 0;
arrayMarkers[idx] = [];
var mapLatlng = new google.maps.LatLng(40.6029248937, 7.7861327300);
var mapOptions = { center: mapLatlng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.SATELLITE };
var map = new google.maps.Map(document.getElementById("karte"), mapOptions);
var bounds = new google.maps.LatLngBounds();
arrayMarkers[idx]['breite'] = 44.4114053473682;
arrayMarkers[idx]['laenge'] = 8.91858100891113;
arrayMarkers[idx]['farbe'] = "http://new.kfb.localhost:8888/img/ico/button2_gruen.png";
arrayMarkers[idx]['hafen'] = "Ab/bis Genua";
arrayMarkers[idx]['link'] = "Karte, Wetter und<br>Landausflüge für<br><a href='hafen.php?hafen=172'>Genua</a><br>Sa, 16.03.13";
idx++;
arrayMarkers[idx]['breite'] = 43.3449053146323;
The error is thrown at the last line, right after the index has been incremented. Any ideas what the problem is?
Thanks MK
Upvotes: 1
Views: 5881
Reputation: 1074028
You're incrementing idx
, and then doing this:
arrayMarkers[idx]['breite'] = 43.3449053146323;
You've never put any object at arrayMarkers[idx]
, and so you end up trying to add a property to undefined
, which causes an error.
If you want to create an array at the new index, add the second line shown here:
idx++;
arrayMarkers[idx] = []; // <=== Add this
arrayMarkers[idx]['breite'] = 43.3449053146323;
Side note: The things you're putting in arrayMarkers[idx]
are arrays ([]
), but you're not using them as arrays, you're using them as objects. You can do that in JavaScript (because those arrays aren't really arrays at all), but unless you're going to make use of the fact they're arrays, I'd just use objects:
arrayMarkers[idx] = {}; // Instead of []
Upvotes: 6
Reputation: 46900
idx++;
arrayMarkers[idx]['breite'] = 43.3449053146323;
should be
arrayMarkers[idx]['breite'] = 43.3449053146323;
idx++;
So that you move to next index after all operations are complete. Using them otherwise increments the value to next index which does not exist
Or if it has to stay the same way then you can initialize that value like
idx++;
arrayMarkers[idx] = [];
arrayMarkers[idx]['breite'] = 43.3449053146323;
Upvotes: 0