在 javascript 中创建对象数组,然后获取属性

Creating an array of objects in javascript, then fetching properties

所以我现在正尝试在 javascript 中重新创建 2048,但遇到了一些麻烦。基本上,我的想法是将网格创建为一个包含 16 个对象的数组,这些对象采用坐标和一个布尔变量来表示它是否填充了一个图块。

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

      }
    }
}

然而,当我尝试打印块的分配值时,它说它们未定义

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

给我

"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"

简单地添加一个新的前块。

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

工作示例:http://jsbin.com/filerocoso/1/edit?js,output

访问变量使用:

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

编辑:Jordon 先于我,还更新了示例并显示了数组的正确访问 属性。

您需要在您的代码中使用 new 关键字,并更改您访问块数组的方式检查一下:

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