1

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"
tag00
  • 13
  • 2
  • In addition to the below answers you should capitalize the name of the constructor function by convention ... like Block. Plus what's the point of double name assignment..? – Redu Apr 27 '16 at 00:17
  • Capitalized it. What do you mean by double name assignment? Calling both the variable and function "block"? – tag00 Apr 27 '16 at 02:09
  • Yes, you don't need to do that as a common practice. For your fingers good. – Redu Apr 27 '16 at 07:39

2 Answers2

4

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);
omarjmh
  • 13,632
  • 6
  • 34
  • 42
1

Simple add a new before block.

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

working example: http://jsbin.com/filerocoso/1/edit?js,output

To access the variable use:

console.log(blocks); console.log(blocks[0].xcord); // first item in array, property xcord

Edit: Jordon beat me to it, also updated example and show correct access of array property.

seN
  • 1,045
  • 14
  • 21