In Javascript, when using `console.log(arr.length)`, the length appears to be `n`. However, when using `console.log(arr)`, the length appears to be `n-1

One line will output a value of 10, while the next will print one less:

console.log("ds length: " + ds.length); // Outputs 10
console.log(ds); // Displays all elements except the last and reports the length as one less.

All relevant sections of my code are contained within the singleton AS object:

FindPath: function(oX, oY, dX, dY) { // origin, destination
        var heap = AS.Heap();

        var g = AS.Grid; // Declared in AS as: Grid: new Array(),

        var node;

        var cn = g[oX][oY]; // current node
        var dn = g[dX][dY]; // destination node

        heap.push(cn);

        cn.CoorType = AS.CoorType.VISITED;

        while (heap.length > 0) {
            cn = heap.pop();

            if (cn === dn) {
                var ds = new Array(); // direction set (instructions)
                var pn;// parent node;

                do {
                    pn = cn.Parent;
                    ds.push({
                        Dir: cn.Y - pn.Y !== 0 ? cn.Y - pn.Y < 0 ? AS.Direction.UP : AS.Direction.DOWN : cn.X - pn.X > 0 ? AS.Direction.RIGHT : AS.Direction.LEFT,
                        Node: cn});
                    cn = pn;
                } while (pn.Parent);

                console.log("length of ds: " + ds.length);
                console.log(ds);

                AS.CleanUp();
                return ds;
            }

            // The following code eliminates the use of functions to improve performance, due to lag issues when calling FindPath() multiple times quickly in a large area.
            node = g[cn.X+1][cn.Y];
            if (node.CoorType === AS.CoorType.NOTHING) {
                node.CoorType = AS.CoorType.VISITED;
                node.Parent = cn;
                node.Score = ((Math.abs(node.X - oX) + Math.abs(node.Y - oY)) * AS.SMALL_ADVANTAGE + Math.abs(node.X - dX) + Math.abs(node.Y - dY)) +
                        Math.abs((node.X - dX) * (oY - dY) - (node.Y - dY) * (oX - dX)) * 0.0001;
                heap.Sink(node);
            }
            // Repeat similar block for other directions...

        }

        AS.CleanUp();
        return heap; 
    },

Heap: function() {
    var heap = new Array();

    heap.Sink = function(node) {
        var i = this.length-1;

        while (i > 0 && this[i].Score < node.Score) i--;

        this.splice(i, 0, node);
    };

    return heap;
},

CleanUp: function() {
    var x, y, g = AS.Grid;

    var limX = g.length - 3;
    var limY = g[0].length - 3;

    for (x = 2; x < limX; x++) {
        for (y = 2; y < limY; y++) {
            if (g[x][y].CoorType === AS.CoorType.VISITED) {
                g[x][y].CoorType = AS.CoorType.NOTHING;
                delete g[x][y].Parent;
            }
        }
    }
}

I discovered that at times, the objects moving based on the path returned by FindPath miss a step. Upon further investigation, I found the pattern described above.

Answer №1

When I added two lines within the do {} while (pn.Parent) loop:

do {
    pn = cn.Parent;
    ds.push({
        Dir: cn.Y - pn.Y !== 0 ? cn.Y - pn.Y < 0 ? AS.Direction.UP : AS.Direction.DOWN : cn.X - pn.X > 0 ? AS.Direction.RIGHT : AS.Direction.LEFT,
        Node: cn});
    console.log(ds.length); // This line was added,
    console.log(ds);        // along with this one
    cn = pn;
} while (pn.Parent);

I noticed that console.log(ds) was displaying the content of ds after a call to GameLoop(), which would eventually trigger AS.FindPath, while console.log(ds.length) displayed the length of ds at the moment it was requested to be printed.

Since, just before the end of GameLoop(), I was removing the last element of the path returned by FindPath() (nextDirection = path.pop()), console.log(ds) would show one less element.

Dealing with javascript can be frustrating when it reveals the future state of an object instead of its current state during console.log()...

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

Having trouble accessing the property 'top' of an undefined object in your Ruby on Rails project?

After thoroughly reviewing all the similar threads on SO regarding this error, none of them provided a solution that worked for me. Here is the flow of events: Go to the new Customer page, fill out the required fields, and click save Invoke a method in ...

What is the best way to retrieve the "value" property of an <input> element in HTML?

Imagine there is an <input> element. When using jQuery to get the attributes of this element, I have written the following code: console.log($("#radio").attr("type")); console.log($("#radio").attr("value")); <script src="https://cdnjs.cloudflar ...

Is there a way to get a Chrome extension to run automatically in the background?

I am looking to develop a custom chrome extension with a countdown timer functionality that automatically runs in the background. However, I am facing an issue where my background.js file is unable to access the popup.html file. How can I execute scripts i ...

Creating a function that counts the number of times a button is clicked

I want to have the "game" button appear after the user clicks the "next-btn" 2 times. Once the multiple choice test has been completed twice, I'd like the game button to show up and redirect the user to a separate HTML page called "agario.html." I&ap ...

What are some methods for extracting a value from a separate webpage and saving it as a variable in my code?

I am utilizing graphite to obtain statistics and would like to display a justgage gauge for a specific variable. Graphite provides values in either JSON format: [{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}] o ...

How can the dependencies object be extracted from the package.json file in an Angular project?

Scenario: I am managing multiple Angular applications within the same project. Whenever I need to upgrade an npm package, I find myself having to manually update the package.json files in each application. While I attempted a mono repo approach, it did not ...

Is there a way to make the onKeyDown event function properly in Next.js/React?

I'm currently developing a website with Next.js and am facing an issue trying to execute a simple function when a key is pressed. Strangely, the onKeyDown event isn't getting triggered as expected in my code snippet: <main onKeyDown={e => c ...

The RemoveObjectAtIndex function is ineffective

I'm having trouble deleting an object from my Array in Xcode 6.3.1 with Objective-C. Below is the code I've been trying: [array removeObjectAtIndex:2]; However, when I run it, I get this error message: No visible @Interface for "NSArray" de ...

Utilizing use-immer and promises to effectively handle an API route mapping system

In the process of tackling the issue of double hook calls in Next.js dev mode, I've encountered a challenge with server API calls that cannot handle duplicates. To address this, I opted for fix #4 outlined in the following article, where I decided to ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

What is the best way to display errors from a Node backend on a React frontend?

When making an API call, I am encountering multiple errors. My goal is to display relevant errors from the backend on the frontend. For example, I would like to indicate the error 'Site name exist' on the frontend. Backend: if (Sname) { cons ...

extract data from text node using selenium

Currently, I am working on a web application and testing it with Selenium. Within my code, there is a specific node that I am trying to extract data from. <span>Profile Run <span class="current">23</span> of 29</span> My main obje ...

In C, when you assign a pointer to point to another pointer, it will ultimately lead to a null

Currently, in my C program, I am working on creating a data structure that involves an array of pointers to another structure. The specific array declaration for this structure called Bucket is as follows: Bucket *b_array[]; This array is a part of anothe ...

Executing functions in Node.js

I have a query regarding the execution of functions in Node.js. Check out the code snippet below: const dynamic = require('dynamic'), obj1 = dynamic.obj1, obj2 = dynamic.obj2; const myFunction1 = () => { let x = obj1; ...

The module could not be found because there was an error: Unable to locate '@mui/icons-material/AddCircle', despite the fact that @mui/icons-material has been installed

When working with the IR compiler in Kotlin JS, I encountered an issue. The error message reads: Module not found: Error: Can't resolve '@mui/icons-material/AddCircle' Even though @mui/icons-material is already installed, the error persist ...

What is the best way to retrieve a return string from an external program using XPCOM in Firefox?

Is there a way to execute an external program in XPCOM and retrieve the actual return string from it, instead of just the return code? I have researched nsICommandLine, nsICommandLineHandler, nsICommandLineRunner, and nsIProcess but it seems like none of ...

Using Ionic 3 pipe for filtering lists based on comparison of 2 arrays

Looking for assistance in creating a customized filter PIPE component that can filter and display job postings based on selected search array words. I have been able to return results using one search value, but now need help modifying it to handle multipl ...

What steps should be taken to retrieve a promise returned by a function?

I am a beginner when it comes to working with promises in JavaScript, so any help is greatly appreciated. I have written some code that tries to fetch data from the Firebase database and pass a list of courses from main_page.js to index.js through a functi ...

Executing a For Loop in Java Script while integrating it with SNS message notifications

Java Script is still quite new to me and I could really use some assistance with a specific issue in the code snippet below. I am using an IF Statement to validate an incoming SNS Message. If it matches, I want to display the message values. else if (ob ...

Organizing routes in Express.js and AngularJS

Having trouble setting up an express + angular app. Successfully loaded the assets files into it. Upon examining my code for Express and the html file, it seems that Express is only returning the index.html file, causing all routes to return that file. ...