Implementing a 2D boolean array as a member variable in P5JS

While working in p5js, I am trying to create a 2-dimensional boolean array in JavaScript. The following code snippet successfully creates a 3x3 array of booleans set to false:

var cells = Array.from({ length: 3 }, () => 
    Array.from({ length: 3 }, () => false)
);
console.log(cells)

However, when I attempt to create this array as a member variable of a class, the values remain false regardless of any changes:

class ExampleClass{
    constructor(){
        this.cells = Array.from({ length: 3 }, () => 
            Array.from({ length: 3 }, () => false)
        );
        this.cells[0][0] = true;
        console.log(this.cells)
    }
}

Even if I try to assign and manipulate the array outside of the class context, the values still default to false:

var cells = Array.from({ length: 3 }, () => 
    Array.from({ length: 3 }, () => false)
);
cells[0][0] = true;
this.cells = cells
console.log(this.cells)

I suspect there might be a flaw in my understanding of how JavaScript initializes variables. How can I fix this issue and ensure that the array remains mutable even when declared as a member variable?

Answer №1

It's unclear why the results you're seeing differ from what is expected. Unfortunately, with the limited example provided, I'm unable to replicate the error:

class SampleClass{
    constructor(){
        this.cells = Array.from({ length: 3 }, () => 
            Array.from({ length: 3}, () => false)
        );
        this.cells[0][0] = true;
        console.log(this.cells);
        this.cellSize = 100 / 3;
    }
    draw(){
      for(let i = 0; i < this.cells.length; i++){
        for(let j = 0; j < this.cells[i].length; j++){
          fill(this.cells[i][j] * 255);
          rect(i * this.cellSize, j * this.cellSize, this.cellSize, this.cellSize);
        }
      }
    }
}

function setup(){
  createCanvas(100, 100);
  let sample = new SampleClass();
  sample.draw();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

It's possible that the issue lies within certain browsers or other components in a larger program where you are integrating this code.

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

Getting the first array from a fetch promise is a process that involves accessing the

When working with a fetch promise, I need to return a JSON object that contains all of my data. The challenge is that I am not sure what the object name will be. What I do know is that there will always be one object present. Below is an example of my cod ...

Manage an error request with unique parameters

I recently made a GET request using axios in my web application: axios({ method: 'get', url: "example.com", params:{ _id: "anId" } }) .th ...

Pass a set value in Vue configuration

I need to create a form where users can edit information from a database. The challenge is to display the current value in the input field so users can choose to change it or leave it as is. Here's how I'm attempting to achieve this: <div v-f ...

It can be frustrating to have to refresh the page twice in order to see changes when utilizing the revalidate feature in Next

When I make the REST call to fetch data for my page using the code below: // src/app/page.js const Home = async () => { const globalData = await getGlobalData(); return ( <main'> <SomeComponent data={globalData} /> < ...

angular-chart custom tooltip positioning issue

Hello everyone! I'm having trouble fixing the tooltip position when hovering over a point. I've searched through various posts on StackOverflow and have tried all the examples provided in my implementation: https://github.com/chartjs/Chart.js/tr ...

Can someone explain how to use JavaScript to make table data fill the entire row in a table?

After clicking the button, the layout of the table changes. I want to keep the original table layout even after the JavaScript function runs. I am still learning about JavaScript. function toggle(button) { if(document.getElementById("1").value=="Show ...

Ways to identify when the socket has been opened by the client?

When utilizing socket.io on the client browser side, is there a way to identify when the socket connection has been successfully opened? I am also interested in monitoring other standard messages such as errors and disconnections. In comparison to the Web ...

Polymer Google Maps Marker OnClick Function

I am struggling to trigger a click event for a google maps marker while utilizing the Polymer web component. After reviewing this question on Stack Overflow, I have noticed a minor difference in my code that may be causing issues. My implementation invol ...

Using JSON in Highcharts: Customizing Border and Label Colors

Currently using Highcharts in JSON format with the following syntax: var neutral_color = '#c4c4c4', medium_grey = '#929292'; lineChartJSON['chart']['plotBorderColor'] = medium_grey; lineChartJSON['chart&ap ...

Connecting JavaScript and HTML in EclipseWould you like to know how to link

After completing the Rock Paper Scissors exercise on Codecademy, I wanted to transfer it to my Eclipse IDE. The code worked perfectly on the Codecademy platform, so I copied everything and created a .js workspace in Eclipse to paste it there. Now, my ques ...

Emberjs 1.0: Data Changes don't Refresh Computed Property and Template

In my Ember.js application, I am using a datepicker which is integrated for selecting dates. When a date is clicked on the datepicker, a computed property should compare the selected date with the dates available in the timeslot to check for a match. Based ...

Triggering the react state update function through an onClick event

Trying to grasp React through a tutorial, but I'm confused about why I need to create a new function to pass to an JSX onClick instead of using the one returned from a React useState call directly. The following code works because it uses the handleB ...

Mongoose Express: Limiting increments to a maximum of 5

Currently, the essential functionality implemented is 1 click = 1 vote. The system successfully updates a vote parameter in MongoDB and increments it as expected. However, after approximately 5 votes, the incrementing process halts. Upon refreshing the bro ...

Smart method for organizing browsing history

I'm currently working on enhancing the navigation in an AJAX application. Here is my current approach: Whenever a user clicks on an AJAX link, the corresponding call is made and the hash is updated. Upon loading a new page, I verify if the hash exis ...

Patience is key: techniques for real-time variable updates and calculations in JavaScript

Hi, I am currently working on creating a dashboard to calculate the total outstanding amount for my medicine suppliers using Next.js. Below is the code snippet for my "createPurchase" API: import PurchaseOrder from '../../models/PurchaseOrder' ...

Transferring data between Promises and functions through variable passing

I am facing a challenge. I need to make two separate SOAP calls in order to retrieve two lists of vouchers, and then use these lists to perform some checks and other tasks. I have placed the two calls within different Promise functions because I want to in ...

Chart.js outdated data not being cleared

This query has been repeated numerous times, and despite my efforts to find a solution in previous discussions, I have not been successful. As part of the reporting feature, I am creating multiple bar charts using a for loop. I am utilizing node.js with ...

Maintaining my navigation menu as you scroll through the page

I've been working on creating a website for my business but I'm facing a challenge. My goal is to have a fixed navigation bar that stays in place as people scroll down the page, similar to what you can see on this website: (where the navigat ...

Discover how to access the rotation of an object within ThreeJS based on

Currently in my code, I have implemented rotation restrictions around a specific axis using the following snippet: if (obj.rotation.x > -0.5) { // execute rotation } Initially, this setup worked perfectly. However, things took a turn when I introd ...

Guide to utilizing Materialize with Angular 2

For the past 2 days, I've been struggling with an issue. I'm fairly new to Angular 2 and I'm attempting to use Materialize with Angular 2. I managed to resolve a couple of errors that were asking me to update the TypeScript version, which I ...