When array.push is used inside another array, it results in an undefined value

While working on defining an array within the Fire array in my code, I encountered a problem.

When I tried to use console.log() to display the length of the array inside the Fire[] array for debugging, I received an error indicating that the array was undefined. Here's the snippet of my code:

var Fire = [];

var fire = function FireGen()
{
    this.particle = [];
    var part = function Particle()
    {
    };
    this.particle.push(part);
};
Fire.push(fire);

console.log(Fire.particle.length); //Outputs undefined

As someone who is relatively new to using objects and arrays in JavaScript, I would greatly appreciate it if someone could shed light on why my array is ending up undefined.

Answer №1

It has been mentioned by others that Fire is an array, meaning to access properties of the first element from that array, you must use Fire[0].... However, your code has a few other issues that require attention.

Both your FireGen and Particle functions seem to be defined as constructor functions (utilizing this in the function body). Therefore, you should invoke these functions with the new operator, for example, new FireGen(). After making this adjustment, it is advisable to reorganize your code so that x and y are passed in as arguments, and each function is only defined once.

Here is an example:

var Fire = [];
function FireGen(x, y)
{
    this.x = x;
    this.y = y;
    this.particle = [];
    this.particle.push(new Particle(x, y));
};
function Particle(x, y)
{
   this.x = x;
   this.y = y;
};

function spawnFire(event)
{
    var x = event.clientX;
    var y = event.clientY;
    Fire.push(new FireGen(x, y));

    console.log(Fire[0].particle.length); //Outputs undefined
}

document.addEventListener('click', spawnFire);

Answer №2

When you define functions within an array without executing them, they are not functional. It seems like you are trying to push functions into an array, but the array lacks a proper particle property for the functions to be stored.

To achieve the desired functionality, consider the following approach:

var Fire = [];

var fire = {
  particle: [
    {
      part: { /* ... */ }
    }
  ]
}

Fire.push(fire);

console.log(Fire[0].particle.length); //Outputs 1

Answer №3

When you use push(part) and push(fire), you are actually pushing function definitions.

To make these function as classes, utilize the new operator. For example, use push(new part) and push(new fire).

Furthermore, keep in mind that Fire is an array, so you will need to specify an index (such as Fire[0] for the first item in the array).

var Fire = [];

var fire = function FireGen()
{
    this.particle = [];
    var part = function Particle()
    {
    };
    this.particle.push(new part);
};
Fire.push(new fire);

console.log(Fire[0].particle.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

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

How to print a file with the .aspx extension in an Asp.net

While attempting to print the contents of an HTML DIV using the provided code, everything worked smoothly. However, upon integrating an Ajax Control into an Aspx page, an error message surfaced: "Extender control 'CalendarExtender2' is not a r ...

extract the information from a specific div on a different website using JavaScript

My goal is to load a specific div with a class="container" from a website and extract its content into my application. Upon making an ajax call to retrieve the site's data, I encountered a cross-domain origin error since I don't have access to t ...

Having trouble getting Bootstrap 5 to work on Laravel 8? Don't worry, I've encountered the same issue but found

Is it possible to install Bootstrap 5 on Laravel 8? After installing Bootstrap 5, jQuery, and Popper.js using the CDN version, I noticed that the dropdown menu and toggle button are no longer working, although my script is functioning correctly. Here is ...

What is the best practice for storing a SQLITE database file in electron when in production mode?

Currently, I am developing a portable Node.js server using Electron and utilizing an SQLITE database for data storage. During development, the database file test.db is placed in the same directory as my Main.js file, which works perfectly. However, when I ...

Angular ng-bind is incorrectly displaying the value as 'object' instead of the intended value

I am working on an Angular app where I am retrieving data from a service in the following manner: angular.module('jsonService', ['ngResource']) .factory('MyService',function($http) { return { getItems: ...

In the frontend, I seem to have trouble accessing elements of an array using bracket notation, yet strangely it works flawlessly in the backend

I am encountering a peculiar issue as a newcomer to coding. I have an array retrieved from the backend database, and my goal is to access individual elements of this array in the frontend using bracket notation. While I can successfully access the elements ...

Is it possible to make API calls within the componentWillMount lifecycle method in React?

I've been immersed in the world of React for the past year. The standard practice within my team is to make an API call in componentDidMount, fetch the data, and then setState after receiving the data. This ensures that the component has fully mounted ...

Submitting form occurs upon selecting autocomplete suggestion

When a user fills out my form and hits the Go button or presses Enter, the form submits. However, when typing in the text box, it triggers an auto-complete feature after just one character. If the user uses arrow keys to navigate through the auto-complete ...

Why is it that this particular line of code sometimes gives me an "undefined" result before returning an actual value?

Why does the method 'equal' always return with an "undefined" followed by a number? And when I try to parse it, it returns me a NaN. <!DOCTYPE> <html> <head> <script> var fnum = 0; var secondNum; var operation; functi ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

Custom headers in XmlHttpRequest: Access control check failed for preflight response

Encountering an issue with an ajax GET Request on REST Server. Test results and details provided below. There are two methods in the REST Server: 1) resource_new_get (returns json data without custom header) 2) resource_api_new_get (also returns json d ...

Exploring Vue and Webpack: Optimizing global variables for development and production environments

I have been using vue-cli to create my web application. Throughout the app, I am making use of an API by including it in various places like this: axios.post(API + '/sign-up', data).then(res => { // do something }); The API variable is a c ...

The current CLI version is exclusively designed for Angular 5.0.0 or above and may not be compatible with other versions

I encountered an issue with my Angular project that was originally running on version 4. I mistakenly installed version 6 of Angular CLI while setting up a new project, resulting in an error message stating 'Your global Angular CLI version is greater ...

Using Java8 to flatten a JSONArray of JSONObject into a 2D array

Currently, my code utilizes net.sf.json.JSONArray and net.sf.json.JSONObject with JSONArray containing multiple JSONObjects. This is a simplified representation of the structure: [ { "obj1": [ { "ID": 12, ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

Building web navigation using a combination of HTML, JavaScript, and PHP within a category, sub

I've been struggling to find a detailed tutorial on implementing a dynamic website navigation system using javascript or php. It seems like every time I attempt to research this topic, I end up feeling confused and unsure of where to start. My goal i ...

Vim: Turn off autocomplete when using insert mode key bindings

I've set up a mapping in insert mode to automatically indent brackets: inoremap [;<CR> [<CR>];<Esc>O<Tab> When I use it, the result looks like this (the pipe character represents the cursor): const a = [ | ]; Now, I want ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Tutorial: Implementing InfoWindows for Markers in Google Maps API V3 in a C# Web Page

Here's my newbie question, hope the formatting is correct :) I'm working on an ASP.NET, C# application that retrieves coordinates (Lat, Lon) from SQL and displays them as markers (which is working fine). However, when I try to add infowindow ...