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

时间:2016-04-26 23:54:43

标签: javascript arrays object 2048

所以我现在尝试在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"

2 个答案:

答案 0 :(得分:4)

您需要将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);

答案 1 :(得分:1)

在块之前添加一个新的简单。

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打败了我,还更新了示例并显示了对数组属性的正确访问。