Exploring through an array: Error encountered - Unable to access property as it is undefined

As a novice coder, I'm seeking assistance with a basic issue that has me stumped despite my attempts to find a solution. My grid consists of arrays nested within an array named 'cells', filled with 1s and 0s representing live and dead cells. My goal is to search the eight neighboring positions for each cell on the grid using nested for loops:



    //iterate through the entire board
    
    for (y = 0; y < cells.length; y++) {
      for (x = 0; x < cells[0].length; x++) {
        
        let liveNeighbours = 0;
        let deadNeighbours = 0;
        
        //iterate over neighbors in a 9-cell grid, excluding the current cell
        for (yy = y - 1; yy <= y + 1; yy++) {
          for (xx = x - 1; xx <= x + 1; xx++) {
              if (yy !== y || xx !== x) {
                
                if (typeof(cells[yy][xx]) !== 'undefined') {
                  if (cells[yy][xx] === 1) {
                    liveNeighbours++;
                  } else if (cells[yy][xx] === 0) {
                    deadNeighbours++;
                  }
                }

            }
          }
        }
        
        console.log('Analyzing cell at position: ' + x + ', ' + y);
        console.log('Number of live neighbours: ' + liveNeighbours);
        console.log('Number of dead neighbours: ' + deadNeighbours);        
        
        
      }
    }
    
  }
}

Although this method seems straightforward, it sometimes results in attempts to access undefined array indexes (such as cells[-1][-1]). I've attempted to address this by including a typeof check, but I'm still encountering the error:

TypeError: Cannot read property '-1' of undefined

The code fails to execute the typeof operation because the value is undefined, despite my intention to evaluate it. What am I missing here?

Answer №1

An alternative method to consider:

cells[yy]?.[xx]

Implementing the optional chaining operator allows for returning undefined if either cells[yy] or cells[yy][xx] is undefined.

This eliminates the need for an if statement entirely since undefined !== 1 and undefined !== 0.

Previous code:

if (typeof(cells[yy][xx]) !== 'undefined') {
    if (cells[yy][xx] === 1) {
        liveNeighbours++;
    } else if (cells[yy][xx] === 0) {
        deadNeighbours++;
    }
}

Updated code:

if (cells[yy]?.[xx] === 1) {
    liveNeighbours++;
} else if (cells[yy]?.[xx] === 0) {
    deadNeighbours++;
}

Additional note: CanIUse Optional Chaining Operator? (Yes, except for IE)

Answer №2

You are almost there. The issue arises when

typeof(cells[yy][xx]) !== "undefined"
is utilized and the value of yy exceeds the range, leading to an attempt to access a subscript of undefined.

To resolve this, adjust it to:

if (typeof cells[yy] !== "undefined" && typeof cells[yy][xx] !== "undefined")

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 a password with two distinct numbers using regular expressions

In javascript I am struggling to create a password that meets the criteria of having at least eight characters, including two SEPARATE digits, one uppercase and one lowercase letter, as well as one special character (-, @, #, $, &, *, +) but not /, !, ? ...

Retrieve the variance between two arrays and store the additions in AddedList and the removals in RemovedList using typescript

I am still getting the hang of Typescript and I am trying to figure out the best solution for my issue. I have two arrays, A and B, and I need to identify the difference between them in relation to array A. The goal is to separate the elements that were ad ...

The error message "Adyencheckout is not a constructor" is popping up in my

Struggling to implement the Adyen dropin payment UI in NextJS and facing issues initializing the Adyen dropin component. Attempting to dynamically import Adyen web to avoid window is not defined error, but uncertain on how to use it as a constructor after ...

Arranging an array in a personalized order

My data array looks like this: $array = array( 'total_ids' => 0, 'unique_ips' => 0, 'unique_ids' => 0, 'global' => 0, 'total_ips' => 0, ); I want to rearrange it in this order: $array = ar ...

Evolving the appearance of every vacant element

Currently, I am working on a project that allows users to add items. To facilitate this process, I have included an "add another" button which enables them to include additional items all at once. In order to validate the form and save values to the datab ...

(Is it even necessary to use a timezone library for this straightforward scenario?)

As I delve into the realm of time zones for the first time, I've heard tales of how challenging it can be for developers. To ensure I am on the right track, I am posing this question as a safeguard to make sure nothing is overlooked. My scenario is q ...

What causes the scrollbar to not extend to the bottom when connected to another scrollbar via a JavaScript equation?

I have been working on a code that involves multiple scrollbars that are all linked together. When you move one scrollbar, the other two will move proportionally. However, due to differences in width, the scroller doesn't always reach the end of the s ...

Generating a fresh array of unique objects by referencing an original object without any duplicates

I can't seem to figure out how to achieve what I want, even though it doesn't seem too complicated. I have an array of objects: { "year": 2016, "some stuff": "bla0", "other stuff": 20 }, "year": 2017, "some stuff": "bla1", ...

Guide to creating a Map with typescript

I've noticed that many people are converting data to arrays using methods that don't seem possible for me. I'm working with React and TypeScript and I have a simple map that I want to render as a list of buttons. Here is my current progres ...

Guide to defining a conditional statement in a Nuxt.js application

I am working on displaying data from the Wordpress API in a Nuxt.js project. I am trying to organize the data by category, for example where ('post.category ', '=', 'categoryName '). Can anyone help me with the syntax in Vue.j ...

Ensuring the correct range with HTML TextBoxFor

Is there a way to validate user input in a TextBoxFor to ensure it is less than a certain number at run-time? Here is the current code snippet for reference - <div class="col-md-3 input-group"> <span class="input-group-addon ...

Executing a search within the current connection in Node.js

In the code snippet provided, the need is to execute the second SQL query (query2) after constructing it based on the results of the first query (query1). However, even though the second query is successfully built, it is not being executed. Assistance i ...

Tips on preventing the initial undefined subscription in JavaScript when using RxJS

I am having trouble subscribing to an object that I receive from the server. The code initially returns nothing. Here is the subscription code: ngOnInit() { this.dataService.getEvents() .subscribe( (events) => { this.events = events; ...

I am unable to retrieve the length of the variable string

Working on a simple personality quiz with some help from JavaScript. Sounds easy, right? But I've hit a snag. When it comes to the final question, my script checks for an ID called "finalPage" and then uses an if statement to confirm it's there. ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

The previous successful execution of req.body is now yielding an undefined value

My req.body is suddenly undefined, even though it was working fine a few days ago. I've tried using the deprecated body-parser module, but no luck. Here's my code: JS: var express = require("express"); var router = express(); require(& ...

After selecting "ok" on the JavaScript alert dialog, the webpage will automatically refresh, causing all information entered into the textboxes to be erased

<?php include "dbconfig.php"; session_start(); ?> <!DOCTYPE html> <html> <head> <title>Log in</title> <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="stylesheet" type="text/css" href="bo ...

Java program for searching integers in an array using binary search algorithm

Although this question has been asked numerous times before and has many answers already, I am determined to implement my own binary search algorithm in Java. Firstly, I encountered the following compilation error, can anyone explain why? The method mu ...

Utilizing npm packages with grunt: A guide

Initially, when I was working with node.js without grunt, I simply had to write the code below to import an external module. var express = require('express'); However, after transitioning to grunt, I attempted to utilize the qr-image module in ...

Troubleshooting problem with $http in AngularJS: encountering challenges with HTTP JSONP requests

I encountered the following error message while attempting to utilize the JSONP method in AngularJS: Uncaught SyntaxError: Unexpected token : http://example.com/getSomeJson?format=jsonp&json_callback=angular.callbacks._0 Could someone please ass ...