What is the method for initializing a Multidimensional Array of a specific size using Typescript?

Here is the code snippet...

export class Puzzle {
  pieces : Piece[];
  orderedPieces : Piece[][];
  constructor(width: number, height: number){
    this.height = height, this.width = width;
    let total : number = width * height;
    this.pieces = new Array<Piece>(total);
    this.orderedPieces = new Piece[height][width]; // How should I properly initialize this?
  }
  ...
}

In TypeScript, how can I correctly declare a structure like this?

The error message says...

Cannot read property '2' of undefined

Answer №1

As far as I know, there isn't a built-in way to create a multidimensional array in one line of JavaScript code.

You would need to manually initialize each sub-array like this:
this.grid = new Array(this.rows);
for (let r = 0; r < this.rows; r++) {
    this.grid[r] = new Array(this.cols);
}

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

Error occurs with Formik form after selecting an option from a react-select list

Encountering a TypeError in my Formik form when selecting an option from the multiselect react-select list Within the <Formik> component, the Field is rendered like this: <Field name="type" id="type" as={MultiSelectComponent} ...

Using AngularJS to dynamically assign classes with values derived from an ng-repeat loop

I'm attempting to assign a class to a table row using ng-class based on the value of ng-repeat. I have searched online and found examples that involve calling a function. Is it possible to simply set ng-class with a value instead of using a function? ...

The Ionic Image breaks upon publication and installation of the apk

Upon accessing my images using this method, I discovered that they are broken after being installed on an actual device. <ion-avatar item-left> <img src="../../assets/uploads/user.jpg"> </ion-avatar> <h2>{{user?.fullname}}</ ...

Guide to customizing marker colors on APEXCHARTS in a Next.js project

Is there a way to specify the color of each data point individually? For example, something like { x: 'Yellow', y: [2100, 3000], colors: '#808080' }, as the default color is set for all markers under plotOptions > dumbbellColors. I n ...

How to Toggle the :invalid State to True on a Dropdown Element Using JQuery

$("#select_id").is(':invalid') false Is there a way to change it to true? $("#select_id").addClass(':invalid'); $("#select_id").prop('invalid',true) Unfortunately, this method does not seem t ...

What is the process for downloading a .docx file encoded in Base64?

Trying to download a .docx file received from the backend. The object being received is shown below: https://i.sstatic.net/nHKpn.png Download attempt using the following code: const blob = new Blob([fileSource.FileData], { type: fileSource.FileType }); ...

What are the most widely used NodeJS framework and library choices currently available?

I am embarking on the exciting journey of building a robust application using NodeJS. As someone new to Node, I believe it would be beneficial to gather insights from experienced developers in the field. While researching, I have come across positive feed ...

What is the best way to retrieve multiple image file names using JavaScript?

I attempted to use the code snippet below to retrieve the names of all the images I selected, however when I used 'alert', I only received one name even though I selected multiple. My goal is to have all the names of the selected photos saved in ...

Calling GraphQL mutations in ReactPGA

I encountered a 400 Error when making a call from the client to server, and I'm not sure where to start troubleshooting. Oddly enough, when I only include the "id" parameter in the request, everything works fine. However, as soon as I add the additio ...

What sets 'rxjs/operators' apart from 'rxjs/add/operator/'?

Can someone explain the difference between using import { map } from 'rxjs/operators'; and import 'rxjs/add/operator/map'; ? This issue arises in my service method that handles user logins: // import { map } from 'rxjs/operators& ...

Using Jquery to dynamically add an active class to a link if it matches the current URL

Is there a way to modify the code below so that only the exact current URL will have the active class added? Currently, even when the URL is http://localhost/traineval/training, it also adds the active class to http://localhost/traineval/training/all_train ...

JavaScript Error: The code is expecting an object when creating a new instance,

Why isn't this code working as expected? var navbar = document.getElementById("navbar").getElementsByTagName("li"); var hover; var moname; var slider; var newPos=new Object(); var body=document.getElementsByTagName('body& ...

The use of ReactDom.render is no longer permissible in Next.js

I just set up a fresh Next JS application using Next 12. Encountering this issue consistently on every page load in the browser: Alert: The use of ReactDOM.render is no longer supported in React 18. Please switch to createRoot instead. Until you make th ...

JavaScript's concise ternary operation can be used for quick if/else statements when conducting

Here is my current if/else setup: async invoke(request, response) { const { deleted } = request.query; let users = []; if (deleted === 'true') { users = await User.findAndCountAll({ where: { ...

Mongoose consistently fails to properly save dates

I have created a Mongoose model and included a birthdate field in the following way: birthdate: { type: Date, required: [true, "Please enter a birthdate"], lowercase: true, validate: [isDate, "Please enter a valid birthdate&q ...

Error: The window object is not found in this context when initializing the Commerce module from the commerce.export.js file located in the node_modules folder within the @chec

I have been working with the pages router and custom app file (_app.js) https://nextjs.org/docs/pages/building-your-application/routing/custom-app It seems that the issue may be within my _app.js file, where I have the following code: import '../glo ...

Contrasting deleting a node_module folder with running npm uninstall to remove a specific package

Do manual deletion of a package directly from the node_modules folder and running npm uninstall really make any difference, considering that npm just deletes the package anyway? ...

Removing vacant rows from a table using Jquery in asp.net mvc

In my partial view, I am using BeginCollectionItem to manage the code. <tr> @using (Html.BeginCollectionItem("QuoteLines")) { <td> @Html.HiddenFor(m => m.QuoteID) @Html.HiddenFor(m => m.QuoteLineID) </td> ...

Ways to incorporate onload animation into a Pie chart with billboard js

I am currently working on implementing a pie chart with animation using billboard js. However, I am facing difficulties in applying the onload animation. Can anyone provide guidance on how to achieve this? For reference, you can view an example of the des ...

Using Angular to dynamically append HTML elements in a form with ng-repeat

Hey there, I'm looking to create a dynamic form using Angular. I want the button click on this form to append HTML with ng-repeat functionality. Although the button click has an action, I'm having trouble appending data to ng-repeat. I need to ...