trouble encountered when trying to form an array with attributes sourced from a different class (using typescript)

Having trouble creating an array of objects from one class in another class. When I try to push them, an error occurs saying "Cannot read property '0' of undefined." Any help would be greatly appreciated. Here is an example using typescript:

export class Vector {

private elements:Array<number>

constructor(n:number, k:number){
    this.elements = []
    for (let i=0; i<n; i++) {
        this.elements.push(Math.floor(Math.random()*k)+1);
    } 
}

}

class Matrix {

private elements:Vector[];

constructor(n:number, m:number, k:number) {
   this.elements = new Array();
   for (let i=0; i<n; i++){   
        for (let j=0; j<m; j++) {
            this.elements[i][j].push(Math.floor(Math.random()*k)+1)
        }    
    }
}

}

Answer №1

One important correction to note is that instead of this.elements = new Array, it should be this.elements = new Array().

Additionally, trying to use this.elements[i][j].push() will not work because this.elements[i][j] has not been defined yet and you cannot push to something that is undefined.

The corrected code should look like this:

constructor(n:number, m:number, k:number) {
    this.elements = new Array();
    for (let i=0; i<n; i++){
        this.elements.push(new Array());
        for (let j=0; j<m; j++) {
            this.elements[i].push(Math.floor(Math.random()*k)+1)
        }    
    }
}

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

Creating an image using the @aws-sdk/client-bedrock-runtime package is a simple process

Having crafted a BedrockRuntimeClient using typescript, I'm stumped on how to call upon the model and execute the command. const client = new BedrockRuntimeClient({ region: "us-east-1", apiVersion: '2023-09-30', ...

Ways to create loops in Excel without using macros

Sorry for repeating the question, but I am unable to comment due to lack of reputation. I am faced with a similar query as How to loop in excel without VBA or macros?, however, I need to explore recursive loops in Excel without macros for a slightly differ ...

Retrieve objects from an array that contain a certain specified key

I am trying to extract the objects from All_reports that contain the key: comentarioAdmin. Currently, I am retrieving all reports from All_reports, but I only want the reports that have the key comentarioAdmin. Thank you! getReports() { this.Service.g ...

When using MERN Stack (with Typescript) on DigitalOcean, encountering an issue where HTML files are displayed instead of JS and

Upon checking the console, I encountered this https://i.sstatic.net/PWoT5.jpg The app has been developed using Ubuntu and Nginx so far with no firewall configuration yet in place. This is my first time deploying a MERN stack and utilizing DigitalOcean. ...

Combining multiple datasets in Javascript with a constant value of [0] to calculate the sum

Being a beginner, I am seeking assistance with my variable chartdata that serves as a basis: var chartdata = { labels: [ "Bar 1", "Bar 2", "Bar 3", "Bar 4", ], datasets: [ { label: "Green data", type: "bar", dat ...

Issue NG1006: Class has two conflicting decorators applied

I encountered an issue while compiling my project: PS C:\Users\hasna\Downloads\A La Marocaine git - Copie\ALaMarocaineFinal\frontend\src\app> ng serve Compiling @angular/forms : es2015 as esm2015 An unhandled exc ...

Arranging Letters in a Two-Dimensional Array in the C Programming Language

char c; for (c = 'A'; c <= 'Z'; ++c) { for(int i =1; i < newGui->width; i++) { //for (c = 'A'; c <= 'Z'; ++c) newGui->gui[0][i].graphics = c; } ...

Developing a search feature using Angular 6 with Observable subscription for the FrontEnd application

I have a unique challenge where I need to implement a full text search in the FrontEnd due to restrictions with the API. When the frontend starts up, it fetches all data entries from the Backend and subscribes them inside a component using an async pipe. T ...

Is it common to encounter errors in PHP when combining multiple classes together?

I am in the process of developing a website with the following structure: class main { } class mysql extends main { } class user extends main { } class etc extends main { } The main idea is for these classes to utilize functions from one another. Howe ...

Using JavaScript, divide a string containing elements of unknown length that may be adjacent based on their type

If I have a string representing an SVG path like: "M72 0v754h405v-86h-311v-211h302v-86h-302v-285h311v-86h-405z" My goal is to transform it into an array where each element consists of either a letter or a positive/negative number. For example: [ ...

What is the most efficient method for defining a string structure in TypeScript?

Consider the following example of a JavaScript object: const myObject = { id: 'my_id', // Base value which sets the structure for the following values (always pascal case). upperID: 'MY_ID', // Uppercase version of `id`. camel ...

Having trouble with a one-dimensional array of multiples of 5 in my coding practice. It's a new concept for me and I'm

Here is the task at hand: Create a program that will assign and store the first 20 multiples of 5 in an array called Data. No other array can be used in this program. The program should output the elements of the array as follows: a) Write only the com ...

Generating matrices in MATLAB

Is there a way to create an array in Matlab that allows me to store multiple user inputs without replacing the previous ones? As a beginner, I appreciate your patience with me. Thank you! ...

The possibility exists to instantiate the function with an alternative subtype of constraint

When working with TypeScript, encountering an issue where the debounce function refuses to compile due to a problem with the type of the wrapping function: export function debounce<F extends ((...args: any[]) => void)>(fn: F, timeout: number): F ...

Using Typescript to assign a new class instance to an object property

Recently, I crafted a Class that defines the properties of an element: export class ElementProperties { constructor( public value: string, public adminConsentRequired: boolean, public displayString?: string, public desc ...

Creating messages from an array using vanilla JavaScript or jQuery

I have an array of objects containing messages that I want to display on my webpage, but I'm unsure how to approach it. [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"}, {"mes ...

Angular 2's subscribe method allows for actions to be taken in response to

There are two buttons, one of which is hidden and of type file. When the user clicks the first button, a confirmation dialog opens. Upon clicking "Ok" in the dialog, the second button should be clicked. The issue arises when all the logic in the subscribe ...

Importing custom pipes in Angular 2 becomes a bit tricky when working with data grouping

As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine. Here is an example of my JSON data: "locations": [ { "id": "ASS", "name": "test center", "city": "Staten Island", "zip": ...

Can models drive reactive forms by automatically mapping them to FormGroups?

Is it possible to automatically generate a FormGroup from a Model? If I have a Model with multiple Properties: Model: Person firstName: string, lastName: string, street: string, country: string .... And I would like to create a basic FormGroup based on ...

How can I modify certain attributes within an array of objects?

https://i.sstatic.net/TKkcV.jpgI need help with updating properties within an object array. Below is my code for reference. I have an object array consisting of two arrays, where the first one contains attribute "first" and the second one contains "last". ...