1

My javascript 2d array seems to always return a length of 0 if I do a push to it from inside a for loop. No matter what I do it gives a length of 0.

I don't know how many devices I'll have entered into mapList, so I need to get the length of the array, but I can't. Online in examples, codepens, jsfiddles, and the likes, I see similar code, which works correctly. I don't understand what I'm doing wrong.

Can someone explain why the length of it isn't incrementing with each new array?

Javascript:

var mapList = [];
function getMarkers(){
    $.getJSON('getDeviceCoords.php', function(jd) {
        for (var i = 0, len = jd.devices.length; i < len; i++) {
            mapList.push([jd.devices[i].nickname, jd.devices[i].latitude, jd.devices[i].longitude]);
    });
}
console.log(mapList); // [] but expands to show each array entry
console.log(mapList.length); // 0

JSON Response:

{
"status": "OK",
"devices": [
    {
        "ID": "12:34:56:78:90:FF",
        "nickname": "Device 1",
        "latitude": "12.3456",
        "longitude": "12.3456"
    },
    {
        "ID": "FF:FF:FF:FF:FF:FF",
        "nickname": "Device 2",
        "latitude": "12.3465",
        "longitude": "12.3465"
    }
]}

Console Output:

▼[]
    ►0: (3) ["Device 1", "12.3456", "12.3456"]
    ►1: (3) ["Device 2", "12.3465", "12.3465"]
     length: 2
    ►__proto__:Array(0)

0
T1960CT
  • 407
  • 7
  • 18
  • 3
    `$.getJSON` is **asynchronous**, so you are logging the array and it's length *before* you've actually put anything into it. – CRice Mar 27 '18 at 17:38
  • 1
    You can bind one customize event, in this event handler, print out the array. In $.getJSON.done(), trigger this event. – Sphinx Mar 27 '18 at 17:42
  • Try logging them inside `$.getJSON`. As @CRice mentioned `$.getJSON` is asynch. – null Mar 27 '18 at 17:43
  • CRice, thank you! I didn't know it was asynchronous (first couple if times using it.) Using that I found .done() thanks to Sphinx as well, and now know how to handle it properly. – T1960CT Mar 27 '18 at 17:47

1 Answers1

1

You are logging the length of the mapList array before the asynchronous callback has completed. Try this:

var mapList = [];
function getMarkers(){
    $.getJSON('getDeviceCoords.php', function(jd) {
        for (var i = 0, len = jd.devices.length; i < len; i++) {
            mapList.push([jd.devices[i].nickname, jd.devices[i].latitude, jd.devices[i].longitude]);
        }

            console.log(mapList); 
            console.log(mapList.length); 
    });
}
caitlin
  • 2,769
  • 4
  • 29
  • 65