openlang

Referencing An Integer Grid

Any reference to pixelGrid through pixelGrid[#][#] makes the code stop working. I've declared pixelGrid in several different ways, without any improvement. Assigning 0 to a value and showing it works, but assigning pixelGrid[0][0], also equal to 0, abruptly breaks things at that point. It doesn't matter whether I access the array in a condition, to update a value, or elsewhere.


var pixelGrid;
for (let row = 0; row < 9; row++) {
    for (let column = 0; column < 9; column++) {
        pixelGrid[row][column] = 0;
    }
}
function redrawPixels() {
    // Shortened for simplicity
    ImageData.data[0] = 0; // Works fine.
    ImageData.data[0] = pixelGrid[0][0]; // Function stops, and ctx.putImageData no longer updates canvas.
}

The conversation continues 2

Follow the reasoning
  1. Permalink

    Before treating a variable as an array, you must initialise it with an array value, for example

    
    var pixelGrid = []; // <- add this
    for (let row = 0; row < 9; row++) {
        pixelGrid[row] = []; // <- and add this
        for (let column = 0; column < 9; column++) {
            pixelGrid[row][column] = 0;
        }
    }
    console.log(pixelGrid[0][0]);
    console.log(pixelGrid[0]);
    console.log(pixelGrid);

    The result is:

    0

    [0, 0, 0, 0, 0, 0, 0, 0, 0]

    [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]

    Note: Checking errors in the console helps you identify problems like these.

  2. Permalink

    You've declared pixelGrid without ever initializing it to a two-dimensional array, which causes the problem.

    Right now you wrote:

    
    var pixelGrid;

    That means pixelGrid is actually: undefined

    This statement then breaks:

    
    pixelGrid[row][column] = 0;

    since what JavaScript effectively attempts is:

    
    undefined[row][column]

    Initialize the array before doing that:

    
    var pixelGrid = [];

Other sides of the same question

  1. Making the sender appear as a label instead of an email address using Java Mail

    Im sending messages through the Java Mail API. On arrival, the inbox displays the address that sent the message. Id like some…

    Replies 2Latest activity java
  2. Dynamics CRM access from TypeScript

    Because my CRM code runs in a webresource, I have to write to retrieve the entity's data. Regrettably, that expression fails…

    Replies 2Latest activity typescript
  3. What date formatting does a Gleam HTTP response header need?

    I want to send a Date header. The required format looks like this: This is my current attempt:

    Replies 3Latest activity gleam