Search code examples
javascriptarraysobject2048

Creating an array of objects in javascript, then fetching properties


so I'm trying to recreate 2048 in javascript right now and having some trouble. Basically, my idea was to create the grid as an array of 16 objects that take coordinates and a boolean variable of whether it is filled with a tile or not.

  var blocks = [];

  var block = function block(xcord, ycord, filled) {
    this.xcord = xcord;
    this.ycord = ycord;
    this.filled = filled;
};

function createGrid(){
    for (i = 0; i < 4; i++){
      for (j = 0; j < 4; j++){

      blocks.push(block(i+1, j+1, false));

      }
    }
}

However when I try to print the assigned values of the blocks, it says they are undefined

console.log(blocks[0].String(xcord));

Gives me

"TypeError: Cannot read property 'String' of undefined
    at raqixa.js:180:47
    at https://static.jsbin.com/js/prod/runner-3.35.12.min.js:1:13891
    at https://static.jsbin.com/js/prod/runner-3.35.12.min.js:1:10820"

Solution

  • You need to use the new keyword with the code you have, and also change the way you access the blocks array check it out:

    Working Example

      var blocks = [];
    
      var block = function block(xcord, ycord, filled) {
        this.xcord = xcord;
        this.ycord = ycord;
        this.filled = filled;
    };
    
    function createGrid(){
        for (i = 0; i < 4; i++){
          for (j = 0; j < 4; j++){
          blocks.push(new block(i+1, j+1, false));
          }
        }
    }
    
    createGrid();
    console.log(blocks);
    console.log(blocks[0].xcord);