What is the reason for X being set to the maximum length during every iteration?

As I work on generating a two-dimensional array of objects, each object has its own X and Y coordinates. The instantiation process seems to be correct as confirmed by console logging and the position in the array aligning with the values.

However, upon logging the final array after assigning positions to instances of the object, I notice that all objects have identical X coordinates, while the Y coordinates are accurate.

let coordinates = Array(30).fill(Array(40)) // creating an empty two-dimensional array.

class Tile {
 constructor(x,y){
 this.x = x;
 this.y = y;
 }
}

for (let x = 0; x < coordinates.length; x++) {
 for (let y = 0; y < coordinates[x].length; y++) {
  console.log({x,y}) // logs {x: 0, y: 0} -> {x: 29, y:39}
  coordinates[x][y] = new Tile(x,y)
 }
}
console.log(coordinates) // logs two-dimensional array with {x: 29, y:0} -> {x: 29, y:39}

I am struggling to understand why this is happening. Despite researching bindings, scope, and alternative methods like using objects instead of classes, I am unable to resolve the issue. Addressing this problem could potentially solve other unexpected behaviors within my program. For instance, when attempting to create a maze using deep travel and recursion, setting the "Visited" property of each tile to true leads to all tiles being marked as visited, halting progression even though they were not traversed.

If anyone can shed light on what may be causing these issues, I would greatly appreciate it. It's frustratingly simple yet perplexing at the same time.

Thank you for your assistance.

Answer №1

The issue lies in the comparison of x within your loop. You should be using the variable y instead to properly iterate over the coordinates array.

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

Overlaying a div on top of an iframe

Struggling to make this work for a while now. It seems like a small issue related to CSS. The image isn't overlaying the IFrame at the top of the page as expected, it's going straight to the bottom. Here is the code snippet: .overlay{ width: ...

Deploying NextJs application with Firebase's static site generation (SS

TL;DR The new data I add to my project is not displaying on the site, even though it's in the database. The issue arises after deploying with Firebase. I created a meetup website using Firebase as the backend. Everything works fine in development mo ...

It appears that the JS function is not being triggered

I am facing an issue with my JavaScript code where a ball is not showing up even though it should. I have an array with only one element, and when that element matches with "F2", the ball is supposed to appear. I suspect there might be a problem with my us ...

Having trouble retrieving array information in Javascript

I've recently started learning programming and JavaScript, but I'm struggling to access data within an array. Below is a snippet of my code: global.arr = []; var id = 12; for (var i=0; i<5; i++) { arr.push(id); id++; } console.log(arr) ...

Encountering the error message "Function.prototype.bind.apply(...) cannot be invoked as a constructor

I'm attempting to implement Controller Inheritance in AngularJS (1.6.9), but encountering an error in the console: Function.prototype.bind.apply(...) is not a constructor. Here's the snippet from the HTML file: <!-- Controller Inheritance --& ...

validating schemas with yup - checking tuples and alternative data structures

I searched through yup's documentation but couldn't find any information on validating tuple arrays and alternative objects. Can someone provide guidance on how to validate an object with these specific properties using yup? interface Example { ...

Ensuring that all checkboxes have been selected

I have 5 checkboxes all with the attribute name set as relative-view. To confirm that all of them are checked, I know how to verify the first and last one: expect(element.find('input[name="relative-view"]').first().prop("checked")).toBe(true); ...

Tips for linking two divs together - one containing products and the other containing options

Seeking assistance with a coding problem related to showing and hiding items within a div based on the div's ID. Specifically, I have a div containing various products and another div with options related to these products. I need help establishing a ...

Issue with passing parameter values in MVC Html.ActionLink

Currently, I am experimenting with MVC for a demonstration and have managed to put together some components. However, I am encountering difficulties with an Html.ActionLink. The goal is to display a series of dropdown lists to the user that must be selecte ...

Exploring the Usage of sessionStorage within the <template> Tag in Vue.js

Is it possible to access sessionStorage in the script section of a Vuejs component like this? <template> {sessionStorage} </template> Whenever I try to call it this way, I consistently receive the error message "cannot read property &apo ...

ngRepeat does not iterate through an array

Presented below is an object: { "_id" : ObjectId("5454e173cf8472d44e7df161"), "questionType" : 0, "question" : "question1", "answers" : [ { "content" : "answer1" }, { "is_true" : "true", ...

Unable to utilize the forEach() function on an array-like object

While I generally know how to use forEach, I recently encountered a situation that left me puzzled. Even after searching online, I couldn't find any new information that could help. I recently started delving into TypeScript due to my work with Angul ...

Discovering shared elements across several arrays in PHP

Is there a way to find the common elements among four different arrays in PHP? I need to compare multiple arrays and identify the elements that they all share. [0] => Array ( [0] => 121186 [1] => MPE129 ...

After installing the latest version of [email protected], I encountered an error stating "Module 'webpack/lib/node/NodeTemplatePlugin' cannot be found."

Upon updating to nextjs version 10.1.3, I encountered an error when running yarn dev. Error - ./public/static/style.scss Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin' Require stack: - /path_to/node_modules/mini-css-extract-plugi ...

Using Javascript to delete a cookie that was created by an AJAX response

Within my Webapp (which is currently running at localhost/myApp/), I am utilizing an ajax call as shown below: $.ajax({ type: "GET", url: "http://localhost:8080/my.module/Login/login?user=abc&password=123", xhrFields: { withCredent ...

Ways to flip the sequence of lines within a div without altering the formatting, word arrangement, and other elements

I need to rearrange the order of my lines while preserving the styling of words and the sequence I have created. Code Snippet: <textarea id="mytext""> Buy - 3 Potatoes $6.25 Sold - 3 Napkins $7.12 Buy - 5 Fries $11.62 Sold - 7 Pot ...

The attachment with Ajax is not displaying any file data

I am encountering an issue while attempting to send an email to myself along with an attachment. Instead of using the standard php mail function, I have opted for PHPMailer due to its convenience. The data is being processed via an Ajax call after extensiv ...

Refreshing Ads JavaScript and Ad Placements with NextJS Navigation

My NextJS website utilizes a custom JavaScript provided by an ad provider for running ads. The script is typically structured like this: <script type="text/javascript" src="//cdn.adsite.com/static/js/ad.js" ></script> In ad ...

Exploring the versatility of * with string pointers in the C programming language

I'm a beginner in the realm of C programming and I find myself grappling with pointers. My query is thus: when should I include an asterisk (*) when accessing a string pointer, and when is it not necessary? I have come to understand that when I wish ...

What causes the discrepancy in values when accessing globally-declared array elements with both a user-defined function and the main() function?

In my C code, I have implemented a function int* arrayInit(); which assigns values to a globally declared array containing 3 elements and returns the address of the first element. In Segment 1 of the code snippet below, the array elements along with their ...