I am having trouble retrieving the properties of "2d" objects using tiles[i-1], unlike standard objects in JavaScript

I've been working on constructing a random map generator by utilizing a grid composed of tiles within a canvas. In my process, I'm investigating the properties of each tile tiles[i] before handling tiles[i-1]. While this procedure seems to function correctly with "ordinary" objects (method 1), it encounters an issue with "2d" objects (method 2) where the value of tiles[i-1].tileID displays as tiles[i].tileID.

for (i=0; i<40; i++) {
  tiles[i] = { tileID: i}; // METHOD 1
  tiles[i]=c.getContext("2d") // METHOD 2
  tiles[i].tileID = i // METHOD 2
  if(i>0) {
    console.log("my tile ID is", tiles[i].tileID,
    ". The tile ID of the tile before me is", tiles[i-1].tileID)
  }
}

When employing method 1 (and eliminating the two lines from method 2), the console outputs the anticipated outcome:
my tile ID is 12 . The tile ID of the tile before me is 11

However, for method 2, the result differs:
my tile ID is 12 . The tile ID of the tile before me is 12

Is there a rationale behind this behavior (or perhaps another approach I should consider) prior to exploring alternative solutions? Thanks!

Answer №1

One reason for this behavior is that c.getContext("2d") always returns the same object. Therefore, in the following code snippet:

for (i=0; i<40; i++) {
  tiles[i] = c.getContext("2d"); 
  tiles[i].tileID = i;
}

The statement tiles[i] = c.getContext("2d") ends up assigning the same object to each tile in the array. The intention of tiles[i].tileID = i is to assign a new ID to each tile object, but since the tile object remains the same, only the ID gets updated during each iteration.

To correctly store properties for each tile, it is better to create a new object for each individual tile, as demonstrated in method1:

for (i=0; i<40; i++) {
  tiles[i] = { tileID: i}; // METHOD 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

Saving decimal values in a React Material UI textfield with type number on change

I am currently working on a textfield feature: const [qty, setQty] = useState({ qty: "0.00" }); ..... <TextField required id="qty" type="number" label="Qtà" value={qty.qty} step="1.00& ...

Modifying two distinct charts according to the choices made in two independent dropdown menus

In my current project, I am facing a challenge with integrating two separate dropdowns containing UFC fighter names. The goal is to display a plot showing the KD (Knockdown) data for the selected fighters over time when their names are chosen from both dro ...

Converting Node.js Date.toString() output into a time format in Go

My go service is currently receiving data from an external source. Here's how the data appears (in JSON format)- { "firstName": "XYZ", "lastName": "ABC", "createdAtTimestamp": "Mon Nov 21 2 ...

Obtain the origin of the image using dots in Javascript

Sharing my experience with setting a background image using Javascript. Initially, I tried using two dots like this: .style.backgroundImage = "url('../images/image00.jpg')" However, it did not work as expected. So, I removed one dot: .style.ba ...

Verifying user authorization for Microphone access prior to triggering event in React application

I have created a React component featuring a microphone button that operates as follows: OnMouseDown => Initiates audio recording by the user OnMouseUp => Ceases audio recording To elaborate, while the button is pressed down, the user can continue ...

What is the correct way to utilize JSON with AJAX?

I am looking to transfer data from a php backend to a browser using JSON. I have a basic understanding of the process and have included an example code snippet below. However, I have been advised that this may not be the most efficient approach. Due to my ...

Update the user information quickly

In my Express application, I have implemented several routes and a login function. Each user has a balance associated with their data, which is stored in an 'express-session'. However, when the user refreshes the page, I need the balance to be up ...

Tips for altering the appearance of a dropped item using JQueryUI sortable

I have a straightforward website where I need to implement the ability to drag and drop styled DIV elements between two containers. Utilizing JQueryUI's sortable function, this behavior was successfully achieved with the following code: $("#active-co ...

Adjust the Highcharts semi-pie design by eliminating the gap between the pie and the legend

I'm having trouble adjusting the spacing between the bottom of a semi circle donut chart in Highcharts and the legend below it. Despite my efforts, I have not been successful in reducing this gap. Here is the basic chart I am currently working on: h ...

Having difficulty asserting the dual-function button in both its disabled and enabled states

I have a button that is part of a dual-action setup. This button is disabled until a certain event occurs. Here is the DOM structure while the button is disabled: <div class="doc-buttons"> <a href="#" onclick="actualsize();" id="tip-size" cla ...

What is the process of encoding JSON in PHP using jQuery Ajax to send post data?

I created an HTML form to submit data to a PHP file upon hitting the submit button. $.ajax({ url: "text.php", type: "POST", data: { amount: amount, firstName: firstName, lastName: lastName, email: email }, ...

How to bind array elements in Vue.js

I am currently working with an array that contains various arrays and properties within it. My goal is to iterate through the array and generate new rows for each item in it. Here is a snippet of what I have been working on: var orderDetails = [ ...

What steps should I take to ensure my .js.erb files are compatible with Rails 7?

I have been following a Rails Tutorial on Building a Link Shortener with Rails 6 and Ruby 2.xx to create an app. However, I am using Rails 7.0.4 and Ruby 3.0.0. I encountered an issue with my create.js.erb file not functioning properly. After some research ...

What is the best way to change the date format of a JSON string to a custom format?

Hello, I am seeking advice on how to convert a JSON string date from a response into the format of "8/24/2016". I attempted to use a dateFilter.js file, but encountered errors. Here is my attempted code: Below is the dateFilter.js code that resulted in an ...

Do I need to include the title, html, and head tags in a page that is being requested via ajax

I have a page called welcome.htm that is being loaded into another page using ajax. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xh ...

Gaining entry into a JSON object

I'm currently working on a web page that utilizes API data from the Breaking Bad website. I have received this data in JSON format, but I am struggling to figure out how to access only the objects where the "author" is "Walter White." Here is the data ...

JQuery for Seamless Zoom Functionality

I am working with some divs that have images as backgrounds, and I have added a zooming effect on hover. However, the zoom effect is not smooth. Is there a way to modify the script to make the zoom effect smoother? Here is an example of my HTML structure: ...

napi and SWIG: ThreadSafeFunction only runs in a thread after the thread has finished its execution

Check out this repository I created, where a thread-safe function in a SWIG C++ class is executed using node-addon-api. The thread within the SWIG C++ class is triggered using the napi BlockingCallback as shown below: // C++ thread implementation for (int ...

What could be causing the carousel to be hidden in a Next.js project?

My project involves utilizing the react-multi-carousel component to display a maximum of two stock photos. I made modifications to the next.config.js file as well. import Image from "next/image"; import Carousel from "react-multi-carousel&qu ...

What could be causing my component to fail to load properly with Vite?

I have been working on a React project using Vite. Following a tutorial I discovered in an article at https://www.digitalocean.com/community/tutorials/how-to-set-up-a-react-project-with-vite, I encountered an issue. Despite following the tutorial step by ...