1

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

2 回答 2

4

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

工作示例

  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);
于 2016-04-27T00:00:53.320 回答
1

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

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

于 2016-04-27T00:00:28.480 回答