Having trouble with arrays in JavaScript - receiving TypeError when trying to set a property

Issue:

An error has occurred - Uncaught TypeError: Cannot set property '0' of undefined

Snippet of relevant code:

var field = new Array(6);
for(var x=0; x<field.length; x++){
  field[x] = new Array(12);
  for(var y=0; y<field[x].length; y++){
    field[x][y]= new tile();
    field[x][y].type = Math.floor(Math.random()*7);
    field[x][y].subtype[0]=false;//error occurs when this line is executed
    field[x][y].subtype[1]=false;
    field[x][y].subtype[2]=false;
    field[x][y].subtype[3]=false;
  }
}


function tile() {
  var type = 0; type = 0;//int
  var subtype = new Array(4);//Boolean

//+ some functions
}

I am aware that something crucial is missing in the code, but I'm unable to pinpoint it. Can anyone provide assistance?

Update: Additionally, an "Uncaught SyntaxError: Unexpected token this" error was encountered when attempting to add "this." before 'type' and 'subtype' in the tile object. The mistake was due to mistakenly typing

var this.
//instead of
this.

Answer №1

It's important to remember that when setting your tile properties, they should be treated as member properties and prefixed with the this keyword. For example:

function tile() {
    this.type = 0;
    this.subtype = new Array(4);
}

Answer №2

Just wanted to share a quick tip:

If you want to save time while coding, you could try using the following approach:

for(var y=0; y<field[x].length; y++){
  field[x].push(new Tile(Math.floor(Math.random()*7)));
}

And for the constructor:

function Tile(type, subtypes) {
  this.type = type;
  this.subtype = subtypes || [false,false,false,false];
}

This way, a new Tile can be initialized with values provided in the call or set to default values if not specified.

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

Implementing specific CSS styles for images that exceed a certain size limit

Currently, I am facing a dilemma as I work on developing a basic iPhone website that serves as a port for my blog. The main issue I am encountering is the need to add a border around images above a specific size and center them in order for the blog to hav ...

The ExtJS Grid Filter is being triggered excessively

I am working on an ExtJS 6.2 grid that uses the 'classic' API. Although I am not very experienced with Ext, we have a grid component that we reuse with small modifications in different applications. In one of our apps, we have a text field for fi ...

Adding the text-success class to a Bootstrap 5 table row with zebra striping does not produce any noticeable change

I am encountering an issue with a Bootstrap 5 table that has the class table-striped. When a user clicks on a row, I have implemented some jQuery code to toggle the class text-success on the row for highlighting/unhighlighting purposes. The highlighting f ...

Having trouble retrieving data from the json file

Using Ajax to obtain a JSON update: $(document).ready(function(){ $('form').submit(function(event){ event.preventDefault(); var form = JSON.stringify($('form').serializeArray()); $.ajax ({ u ...

Modify the path name in Next.js according to the local environment

In my upcoming next.js project, I aim to dynamically alter the URL according to the language selection of the user. By default, the URL for the English language is set to: http://localhost:3000/en/privacy-policy If the language is switched from English ...

Jquery events continue to accumulate without initiating until the preceding event has completed

Looking at the code below, it essentially fades all the images to 70% within the contact class. When an image is hovered over, its opacity changes to 100%. If multiple images are hovered over or multiple hover events occur in succession, the events will st ...

triggering a method in an Angular controller using a Google API embedded in the view

Using the Google Places Details API, I have included a Google API with a callback function called initMap in the src attribute. Here is the code snippet: <div class="tab-pane active" id="timeline"> <p class="lead">Location</p> <hr& ...

Using React to access a function from a different component in your application

I am working on implementing a topbar menu that requires access to a specific react component. The challenge I am facing is that within the topbar file, I do not directly render the components I need to interact with but still want to be able to call a fun ...

Close the menu when clicking anywhere on the page body

I have successfully implemented a dropdown menu that opens when the navigation button is clicked. However, I am struggling to find a way to close the dropdown menu when the mouse clicks on any part of the page's body. If you have a solution for this ...

What are the advantages of using history.push or another method from react-router-dom compared to simply assigning the path to window.location.pathname?

When I need to navigate within my code, I find it more convenient to simply assign the desired path to window.location.pathname. Can this approach have any drawbacks? ...

Retrieve information from a JSON file containing multiple JSON objects for viewing purposes

Looking for a solution to access and display specific elements from a JSON object containing multiple JSON objects. The elements needed are: 1) CampaignName 2) Start date 3) End date An attempt has been made with code that resulted in an error displayed ...

Is it possible for a single PHP query to manage multiple AJAX requests from various pages simultaneously?

My PHP page is called update_details.php?id=xyz. This page has a query that gets user details and updates their login time. Each user has a unique profile page named profile.php?id=xyz. So, the profile pages are different for each user such as profile.php ...

Is there a way to create a function in JavaScript that eliminates duplicate Objects within an Array of Objects?

Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include: An ID (obtained from the product URL using a function) A color (retrieved through an event listener) A quantity ...

Error in Angular TypeScript occurs when attempting to read properties of an undefined value

Here is the interface that I am working with: export interface IQuest { Id: number, lat: number, lon: number, Question:string, Answer:boolean, IsDone:boolean, Correct:boolean, Range:number} Along with the following component: export class AppComponent imp ...

Multiple card displays not working with Javascript Fetch API

I wrote a script that retrieves data from a URL and then organizes it into tables for display to the user. Initially, the script functioned correctly. However, I decided to enhance its flexibility by introducing two parameters - name and HTML div name wher ...

tips for efficiently loading JSON files using Angular

I currently have a situation where multiple controllers are calling the method getData() from a service. To prevent unnecessary duplicate http calls for the same json file, I have implemented the following approach: QuizApp.service('quizService' ...

Issue encountered: React module not detected while attempting to execute npm start command

While developing my react app, I encountered an issue when trying to run 'npm start'. The application was working as expected until I faced a bug that prompted me to update my node version for a potential fix. After upgrading to node v16.13.2 and ...

SapUI5: Implementing a toggle functionality to display/hide one list item based on another list item's action

UI5 is a versatile framework with numerous possibilities, but sometimes I find myself struggling to implement ideas that would be easier in traditional HTML. Here's the scenario: I want to create a List with ListItems that display cities like Berlin, ...

Displaying or concealing dropdown menus based on a selected option

My goal is to have a drop-down menu in which selecting an option triggers the display of another drop-down menu. For example, if I have options like "Vancouver," "Singapore," and "New York," selecting Vancouver will reveal a second set of options, while ch ...

Implementing jQuery getScript in a Ruby on Rails 3 application

After watching a railscast tutorial on loading records through ajax when a link is clicked, I implemented the following javascript: $(function() { $("#dash_container th a").live("click", function() { $.getScript(this.href); return false; }); } ...