简体   繁体   中英

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"

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM