0

I have create an array of objects on the fly:

var labels = 'ABCD';

downloadUrl('http://www.example.com/locations.php', function(data) {
    var xml = data.responseXML;
    var markersElem = xml.documentElement.getElementsByTagName('marker');

    Array.prototype.forEach.call(markersElem, function(markerElem) {
        var id = markerElem.getAttribute('id');
        var name = markerElem.getAttribute('name');
        var address = markerElem.getAttribute('address');
        var type = markerElem.getAttribute('type');
        var point = {
            lat: parseFloat(markerElem.getAttribute('lat')),
            lng: parseFloat(markerElem.getAttribute('lng'))
        };

        dbRecords = {
            'id': id,
            'name': name,
            'address': address,
            'type': type,
            'point': point,
        };

        markersDbTable.push(dbRecords);
    });
});

console.log('markersDbTable: ', markersDbTable);

var markers =  [];

var markersDbTable2 = JSON.parse(JSON.stringify(markersDbTable));

for (var i = 0; i < markersDbTable2.length; i++) {
    console.log('sdfsdf');

    markers.push(new google.maps.Marker({
            position: markersDbTable2[i].point,
            label: labels[i % labels.length]
    }));
}

console.log('markersDbTable2: ', markersDbTable2);  // values here

The values of id, name, etc are coming from an XMLHTTP request.

if I console.log() the markersDbTable it has values length of more than 1, but if I iterate it using, map(), forEach(), and for() loop, it doesn't go inside those function. I even tried

var markersDbTable2 = JSON.parse(JSON.stringify(markersDbTable));

and console.log() the markersDbTable2, it has no value.

Why is it?

user3856437
  • 2,071
  • 4
  • 22
  • 27
  • 2
    how can we reproduce your problem for test ? – Mister Jojo May 29 '19 at 02:46
  • Please show where you used these `console.log()`s and loops. – Ry- May 29 '19 at 02:52
  • Okay I already updated the description for the code. – user3856437 May 29 '19 at 03:02
  • Guys I again updated the code, sorry about that. – user3856437 May 29 '19 at 03:09
  • 1
    It would be closed as duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). That's the canonical answer for the problem you (and hundreds and thousands of other people) have. tl;dr: you expect JavaScript to be a time traveler. The AJAX-launching code happens instantaneously, then your `console.log` prints empty, then afterwards you get your results. All results from async need to be used in callback (or promise) – Amadan May 29 '19 at 03:10

0 Answers0