Ad

2D Array Data Being Overwritten?

- 1 answer

I have basic code which creates a two dimensional array of an object which holds x and y. When I first instantiate the objects within the array, the data they hold is accurate. But when I get inside a requestAnimationFrame loop the data becomes corrupted and it's no longer accurate? And I can't explain why it's happening

Here's my index.html

<html>
    <head>
        <script src="index.js"></script>
    </head>
    <body>
        <canvas id="canvas"></canvas>
    </body>
</html> 

index.js

window.addEventListener('DOMContentLoaded', (event) => {
    class Pos {
        constructor(y, x) {
            this.y = y;
            this.x = x;
        }
        getx() {
            return x;
        }
        gety() {
            return y;
        }
    }
    var canvas = document.getElementById("canvas");
    let ctx = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    let surfacex = 10;
    let surfacey = 10;
    let surface = new Array(surfacey);

    for (var y = 0; y < surfacey; ++y) {
        surface[y] = new Array(surfacex);
    }
    for (var y = 0; y < surfacey; ++y) {
        for (var x = 0; x < surfacex; ++x) {
            surface[y][x] = new Pos(y, x);
        }
    }

    for (var y = 0; y < surfacey; ++y) {
        for (var x = 0; x < surfacex; ++x) {
            console.log(surface[y][x].getx()+":"+surface[y][x].gety());//THis line prints correctly
        }
    }

    function tick(time) {


        ctx.clearRect(0, 0, surfacex, surfacey);

       for (var y = 0; y < surfacey; ++y) {
        for (var x = 0; x < surfacex; ++x) {
            console.log(surface[y][x].getx()+":"+surface[y][x].gety());//Prints 10:10....no longer correct
        }
    }

        requestAnimationFrame(tick);
    }
    requestAnimationFrame(tick);
});

I run a 2D loop to instantiate then objects, then run the loop again to print their data. Their data gets printed correctly but when I run the loop consecutively inside requestAnimationFrame loop, the getx and gety just keep returning 10:10..

Ad

Answer

In the getx() and gety() methods, you should refer to x and y as this.x and this.y:

class Pos {
  constructor(y, x) {
    this.y = y;
    this.x = x;
  }
  getx() {
    return this.x;
  }
  gety() {
    return this.y;
  }
}

Variables declared using var in Javascript will be 'hoisted'. See MDN for more information on this. Basically it means that if the variable is referenced before it's declared, then you won't get an error, but the variable is accessible (as undefined initially). So the x and y variables in the getx() and gety() methods refer to the x and y variables you're using in your loops. By the time you're executing these methods, you've ran through your loops and the values of x and y will both be 10, which get returned by the class methods.

Ad
source: stackoverflow.com
Ad