【问题标题】:Creating an array of objects in javascript, then fetching properties在javascript中创建一个对象数组,然后获取属性
【发布时间】:2016-08-21 01:04:03
【问题描述】:

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

【问题讨论】:

  • 除了下面的答案之外,您还应该按照约定将构造函数的名称大写...例如 Block.另外,双重名称分配有什么意义..?
  • 大写。双重名称分配是什么意思?调用变量和函数“块”?
  • 是的,您不需要将其作为常见做法。对你的手指有好处。

标签: javascript arrays object 2048


【解决方案1】:

您需要在您拥有的代码中使用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);

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 2015-01-09
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多