Error: Attempting to access index 1 of an undefined property in an array

var grid = [];
    for (var i = 0;i < 6;i++)
    {
        for (var j = 0; j < 6; j++)
        grid[i] = [];
    }

    //Function to determine the number of bombs nearby
    function check(cx,cy)
    {
        var numb = 0;
        if (grid[cx][cy - 1] == "B") numb++;
        if (grid[cx][cy + 1] == "B") numb++;
        if (grid[cx - 1][cy] == "B") numb++;
        if (grid[cx + 1][cy] == "B") numb++;
        if (grid[cx - 1][cy - 1] == "B") numb++;
        if (grid[cx + 1][cy - 1] == "B") numb++;
        if (grid[cx - 1][cy + 1] == "B") numb++;
        if (grid[cx + 1][cy + 1] == "B") numb++;

        return numb;
    }** 

I encountered an error while checking positions with cx +/- 1. I attempted different methods to create the array but was unsuccessful. My goal is to develop a minesweeper game, hence why I am trying to determine how many bombs are near each given index.

Answer №1

verify your function

once the check(0,0) is invoked

if (grid[cx][cy - 1] == "B") numb++;

grid[0][0-1]=

what does 0-1 evaluate to?

Answer №2

To avoid accessing elements in an array that do not exist, a helpful approach is to create a function that takes the array and indices as parameters. This function will return true if the value at the specified indices is equal to 'B', otherwise it will return false.

This check can be done using the in operator along with the logical AND operator (logical AND &&). This combination allows for breaking out when encountering false, while continuing on for true before evaluating the value.

function checkB(array, i, j) {
    return i in array && array[i][j] === 'B';
}

// example usage
if (checkB(grid, cx, cy - 1)) numb++;

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

What is the best way to add child elements to existing elements?

When it comes to creating elements with jQuery, most of us are familiar with the standard method: jQuery('<div/>', { id: 'foo', href: 'http://google.com', }).appendTo('#mySelector'); However, there ar ...

What is the best way to reorganize the switch case in order to invoke methods from a class?

I have a special character called Hero within my game, this Hero inherits characteristics from the Player class and can perform a variety of actions. The majority of these actions are customized to suit the Hero's abilities. class Hero extends Player ...

Error in React Native: The function this.setState is not defined. (The function "this.setState" is not a valid function)

I am working on integrating JSON data from an open source API and storing it as a state. However, I am facing challenges in saving the JSON data into the state which I want to use for city matching. It would be really helpful if someone could provide assis ...

Is there a way to configure json-server, when utilized as a module, to introduce delays in its responses

json-server provides a convenient way to introduce delays in responses through the command line: json-server --port 4000 --delay 1000 db.json However, when attempting to achieve the same delayed response using json-server as a module, the following code ...

What is the best way to update specific values in a react multiselect component?

Within my modal, I have a form where I can edit my model. One of the fields in this form is a multi-select tag field called "tags", which is an array of objects consisting of labels and values as illustrated below. To populate this tag field, I have a dum ...

Ways to create dynamic functionality with JavaScript

I need to iterate through the document.getElementById("b") checked in a loop. Is this achievable? How can I implement it? <img class="img-responsive pic" id="picture" src="images/step1.png"> <?php //get rows query ...

Is it possible to execute a function when the AJAX request is successful and returns a status code of

I am looking to implement the success function to only run a certain function if the status code is 200. I have come across this example: $.ajax ({ success: function(data,textStatus,jqXHR){ external(); } )}; However, I have not found a clear ...

Sending form data via Ajax for a specific field ID

When sending data to an ajax script, I usually create a form tag and assign it an id like this: <form id="myForm"> Then, in the ajax script, I include the following code: data: $('#myForm').serialize(), This sends all the form data. How ...

What steps can be taken to issue an alert when the table does not contain any records?

Upon clicking the submit button, the value from the database is retrieved based on the hidden field ID and displayed in a table. If the value is present, it should load in the table; otherwise, an alert saying 'there is no record' should be displ ...

Invoke a jQuery method in a dynamic manner

Is it possible to achieve the following? var todo = "text"; $this.eval(todo).split(/\b[\s,\.-:;]*/).length; The desired function is: $this.text().split(/\b[\s,\.-:;]*/).length; I'm struggling to find a solution... Ca ...

Using Typescript does not generate any errors when indexing an object with brackets

One interesting thing I've noticed about TypeScript is that it allows me to use bracket notation to access an object via index, even when it only has keys. For example: interface testObject { name: string; id: number; } let first: testObject ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

Custom container width causes animation to crash when scrolling

I'm having trouble with my header. When the containers change with scrolling, an animation takes place. Everything works fine with native Bootstrap CSS, but when I customize the width of the container in my custom CSS (the width set to 1140px), the an ...

Loading an ASP.net page on the client side

Can someone tell me the event for pageload on clientside? function onPageLoad() { setSelectedIndexTo(1); } I attempted to do this, however no changes occur. Appreciate any help. Thanks! ...

The React Bit Dev module is showing a 404 error

Attempting to incorporate the semantic-ui-react table reusable component from the Bit.dev community into my application. The link I am using is: To add this component to your application, use: npm i @bit/semantic-org.semantic-ui-react.table However, when ...

iOS devices do not support the add/removeClass function

This code functions properly on desktop browsers, but encounters issues when used on iPhones. Furthermore, the script mentioned below seems to be causing problems specifically on iPhone devices. var $event = ($ua.match(/(iPod|iPhone|iPad)/i)) ? "touchstar ...

Why am I not receiving any results from the communication between JavaScript and PHP using an HTTP GET request?

Currently, I have a small JavaScript program running within an HTML5 canvas and included a HTTP GET request function in my JavaScript code. The function itself is functioning properly as I tested it with multiple examples from the internet, all of which wo ...

Receiving partial data through the API

My PHP API seems to be experiencing issues when I send data to it using either a post or get request. The strange thing is that the API receives only half of the data. This API functions perfectly fine on localhost, but encounters errors when used on the p ...

Using JQuery to emphasize selected radio button area

Can someone help me modify the code to highlight the checked radio button by adding or removing a class from the <span class " ui-message ui-state-highlight"> element? Below is the HTML and JS code: $(document).ready(function(){ $('# ...

A step-by-step guide on displaying content according to a template file in AngularJS

I am new to using angular js and need help with displaying specific content on a particular page of my web application. I have a HTML template (showContent.html) that generates all pages, but I only want to show certain content on the URL http://localhost/ ...