因此,我现在尝试在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"
最佳答案
您需要将new
关键字与已有的代码一起使用,并更改访问blocks数组的方式将其检出:
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);