How long is a 2D array in JavaScript after adding an element?

My 2D array in Javascript always ends up with a length of 0 when I try to push values into it from within a for loop. It remains empty regardless of my attempts.

The issue arises because I am unsure about the number of devices that will be stored in mapList. Despite looking at various examples online, such as codepens and jsfiddles, where similar codes work perfectly fine, I am still puzzled by what's going wrong on my end.

I'm seeking clarification on why the length of my array isn't increasing with each new entry.

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

Answer №1

Prior to the completion of the asynchronous callback, you are recording the size of the mapList array. To remedy this issue, consider implementing the following approach:

var mapList = [];
function fetchMarkers(){
    $.getJSON('fetchDeviceLocations.php', function(data) {
        for (var index = 0, length = data.devices.length; index < length; index++) {
            mapList.push([data.devices[index].name, data.devices[index].latitude, data.devices[index].longitude]);
        }

            console.log(mapList); 
            console.log(mapList.length); 
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

No Server Response Found for NodeMailer

I am experiencing an issue with my NodeMailer and Gmail API setup for sending emails from my server. The strange thing is that when I test it on localhost, everything works perfectly. However, when I try to run it on my server, NodeMailer doesn't resp ...

Issues encountered with jQuery's $.ajax function when communicating with PHP

I am having trouble creating a simple app that displays data from a MySQL database using PHP and jQuery. The issue I am facing is with retrieving the data using jQuery. While my PHP script successfully returns the data without any problems, I am not receiv ...

Utilizing an if statement with a TypeScript DeepMap Union Type

I am attempting to create a Union type that includes optional fields in its structure. Here are the types I have defined: export type StartEndType = { start_date: string; end_date: string; }; export type PayrollContract = StartEndType & { type: ...

Ways to resolve issues with v-model rendering errors

I currently have code fragments within my index.blade.php file that look like this: The content section: . . . <div class="col-12 col-md-12 mb-3"> <label for="attachment" text-muted">Attachment</label> &l ...

How can I troubleshoot Ajax not loading my additional external JavaScript files?

$(document).ready(function () { $("#livesearch").on("keyup",function(){ var search_term = $(this).val(); $.ajax({ url:"ajax-live-search.php", type:"POST", d ...

Basic inquiries concerning Vue.js and JavaScript

Hey there, I recently developed a small app to practice my Vue skills. However, there are a few features that I would like to implement but I'm not sure how to do it just yet. <div class="container" id="app"> <div class="row"> <d ...

Mapping an array using getServerSideProps in NextJS - the ultimate guide!

I'm facing an issue while trying to utilize data fetched from the Twitch API in order to generate a list of streamers. However, when attempting to map the props obtained from getServerSideProps, I end up with a blank page. Interestingly, upon using co ...

Is there a way to transform a six-digit input into a date format using vue/JavaScript?

I've explored various solutions for this issue, but they all seem to be backend-focused. What I need is a Vue/JavaScript method. I have a string containing IDs, with the first 6 digits representing the date of birth and the final 4 digits being a pers ...

A step-by-step guide on implementing ng-annotate to your code

Is there a way to run ng-annotate through the command line? I am attempting to combine and minify Angular, Angular Routes, and my own script.js into one file. When I use grunt uglify:app1, I encounter an injection error. While my code successfully minifies ...

problems encountered when trying to deploy a backend api on the Render platform

Encountered this error: May 14, 04:27:30 PM - Error [email protected]: The "node" engine is not compatible with this module. Expected version ">=14.20.1". Received version "14.17.0". May 14, 04:27:30 PM - Incompatible module detected. Verified my ...

What could be preventing the jQuery from showing the JSON response?

I am having an issue with a jQuery script that is supposed to pull a quote from an API in JSON format and display it on the page. However, for some reason, I am unable to retrieve data from the API. Can you help me figure out what is wrong here? Thank yo ...

A guide on retrieving form data as a JSON object array in PHP

I am utilizing jQuery Ajax to send form data to a WordPress function. Upon receiving the data in the PHP function as a string, for example "navn=A&navn2=B", I make use of the explode() function to access individual form elements. I believe there must ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

Dealing with Uncaught Type Errors in the Fixed Data Table

I am attempting to implement a fixed data table using the following code snippet. var MyCompi = React.createClass({ getInitialState: function() { return { rows : [ {"id":1,"first_name":"William","last_name":"Elliott","email":"<a ...

Delete auto-generated list using handlebars JS

I have successfully created a dynamic list using Handlebars.js and its template. However, I am now facing confusion on how to remove or delete items from the list using a function or specific code. As I am new to Handlebars, I would appreciate any help. ...

Refine your search by name following the implementation of a character-altering filter

Encountered a scenario in which there is a need to filter elements generated by the 'ng-repeat' directive. I have implemented a custom filter that replaces one character with another and vice versa for each element created. However, when attempt ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...

Using PHP to submit a form depending on user selection

Currently, I am working on a basic input form page that includes a submit button. The goal is to have the data from the form written into my MySQL database based on the user's selection. For instance, if the user chooses option X, I want the input da ...

Execute an xmlhttprequest and then redirect to a different URL

I'm a beginner when it comes to AJAX and JavaScript. My goal is to first show a confirmation box, then send an XMLHttpRequest if confirmed. After that, I want to redirect the user to a new page. Below is my current code: <script type="text/javascr ...

Looking to personalize the appearance of an iframe using CSS styling?

I am working with an iframe that generates a form, and I would like to customize the CSS of this form. How can I go about editing the CSS? <div class="quiz-container" style="text-align: center;" data-quiz="#######" data-pr ...