Retrieving information from an array using a variable results in undefined, but using a specific number returns the desired object

Currently, in the process of learning TypeScript as my second language, I am encountering some challenges with arrays.
I have observed peculiar behavior when accessing the list with a variable as opposed to a hardcoded number.

The code snippet in question is:

class Game {
    data: Array<Array<cell>>;
    size: number;

    constructor () {
        this.data = [];
        this.size = 20;
    }

    initialiseGame() {
        // array of arrays full of cells created here
        this.data = []
        for (let row = 0; row < this.size; row++) {
            this.data.push([]);
            for (let col = 0; col < this.size; col++){
                this.data[row][col] = new cell(row, col);
            }
            // console.log output is as expected at this point
            this.plantBombs();
        }

    getRandomInt(max: number): number {
        return Math.floor(Math.random() * max)
    }

    plantBombs() {
        let randomX, randomY, bombsPlanted = 0;
        
        while (bombsPlanted < this.bombs){
            randomX = this.getRandomInt(this.size);
            randomY = this.getRandomInt(this.size);
            // console.log(this.data[0][0]) shows correct value
            // this.data[randomX] returns undefined
            // this.data[randomX][randomY] throws "cannot read properties of undefined" error
            if (!this.data[randomX][randomY].isMine){
                this.data[randomX][randomY].isMine = true;
                bombsPlanted ++;
            }
        }
    }
}

I utilized Number.isInteger() to verify that the value is an integer and also attempted passing this.data to plantBombs().

Wondering if my approach to accessing the array data is incorrect, or if there might be a simple oversight on my part?

Answer №1

The placement of plantBombs in your code is incorrect

this.data = [];
for (let row = 0; row < this.size; row++) {
  this.data.push([]);
  for (let col = 0; col < this.size; col++) {
    this.data[row][col] = new cell(row, col);
  }
  // previously located here
}
// it should now be placed at this point
this.plantBombs();

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

Errors related to TypeScript syntax have been detected within the node_modules/discord.js/typings/index.d.ts file for Discord.JS

I keep encountering typescript syntax errors after pulling from my git repository, updating all npm modules on the server, and running the start script. The errors persist even when using npm run dev or npx tsc. I've attempted the following troublesh ...

What is the best way to iterate through a JSON file?

Looking at my JSON file: { "stats": { "operators": { "recruit1": { "won": 100, "lost": 50, "timePlayed": 1000 }, "recruit2": { "won": 200, ...

Enhancing a Pie Chart Dynamically with Ajax using Highcharts

I need assistance with updating the data for the pie chart when a list item is clicked. The issue arises when using dynamic values from $cid in data.php. For example, user_student.cid = 1 works correctly, but if I use user_student.cid = $cid, it doesn&apos ...

Retrieve targeted HTML content using AJAX from a webpage that is already being fetched via AJAX

Looking to load a specific div on my webpage via Ajax call, but the content I want to load is itself loaded via ajax. This means I can't get the full HTML content as desired. function loadajax(){ $.ajax({ url: 'http://callcom-com-au.myshopify. ...

Unable to register click event, encountering an error message stating, "co.console.log() is not a function."

I've been attempting to create a button that navigates to another page while passing an object in the parameters. However, I keep encountering an error message: "co. is not a function." It's perplexing because I receive the same error when tr ...

How to customize the button color in a Next.js application

Help Needed: Issue with Changing Default Button Color in Next.JS Web Application. The button text color appears as grey on Desktop Google Chrome, but shows up as blue on Mobile Chrome browser. I want to unify the color to be grey on both platforms. Custo ...

"Having trouble with Set-Cookie Response Header not setting the cookie? It could be due to

My webpage is located at: http://localhost:4201/login When a user clicks on login, it sends a request to: http://localhost:4201/api/login/authenticate This request is then proxied to: The response from the proxy contains a set-cookie header with the f ...

Is it secure to store information that impacts component rendering within a JWT payload?

I am currently developing a MERN app where users have various roles, and different components are rendered based on their role in React. In my application, I store a JWT containing the user's ID and role in a cookie, which is then decoded in a global ...

Error encountered while attempting to execute Typescript with tsc file.ts in the WebGL2RenderingContext

After successfully installing Typescript using both npm and yarn on my Windows 10 machine, I encountered an error when trying to run 'tsc file.ts'. The error message reads '582 declare var WebGL2RenderingContext'. The error traceback p ...

Using the select method in JavaScript arrays

Are the functionalities of JavaScript and Ruby similar? array.select {|x| x > 3} Could it be done like this instead: array.select(function(x) { if (x > 3) return true}) ...

Issue with collecting data in Meteor Collection

After making some edits to another file and increasing the complexity of my application, a tracker function that was previously working fine is now experiencing issues. It is no longer returning any data for vrLoan fundingData This is a snippet of my c ...

What are the advantages of using React JS for a Single Page Application compared to server-side rendering?

Currently, I am faced with a conundrum when it comes to selecting the best approach for a highly scalable project. On one hand, server-side rendering using Node.js with Express (utilizing EJS) to render full HTML pages is an option. On the other hand, ther ...

How can the NavBar be refreshed once a user logs in?

I recently followed a helpful guide on implementing a login system in my React TS application. However, I encountered an issue with the NavBar component within my app compared to how it was coded in the App.tsx file of the guide. Specifically, I found it c ...

Placing a function within an array raises the question: why is the array's value represented as an integer?

There's something puzzling happening in my code. I've placed a setTimeout function inside an array, but when I check the contents of the array using console.log(arr), it only shows an integer value. How is this possible? See the code snippet belo ...

The 'autoComplete' property cannot be found within the 'IntrinsicAttributes & InputProps' type

I'm currently utilizing Typescript and React, but encountering the following error: Property 'autoComplete' is not found on type 'IntrinsicAttributes & InputProps'. This is how I am using the component: <Input ...

data-cy appears in the DOM structure, yet remains unseen

I'm seeking some clarity on how to effectively use Cypress. While writing end-to-end tests, I encountered a failed test due to the element not being visible. A helpful answer I found assisted me in resolving this issue by clicking an element that was ...

Using placeholders with inputs in an Angular2 table generated by ngFor

I have an array public example = [['hallo', 'fruit', 'rose'], ['apple','book']] Currently, I am working on creating a table of inputs. The values in this table depend on the specific part that I am usin ...

Backend data not displaying on HTML page

I am currently working on an Angular 8 application where I have a service dedicated to fetching courses from an API endpoint. The service method that I'm using looks like this: loadCourseById(courseId: number) { return this.http.get<Cours ...

Displaying Stats.js inside a different canvas using ThreeJS

Just starting out with Three.js and wanted to test displaying the Stats.js in a small scenario. Check it out here Decided not to use modules for now, but followed similar code structure as in the examples: var stats = new Stats(); var renderer = ...

Encountering an unanticipated reference error while attempting to paste the data

// Modify the layout function document.addEventListener('DOMContentLoaded', function() { function modifyLayout(productId) { // Referencing the original card and detailed card const originalCard = document.querySelector(&ap ...