1

我有以下代码

for(i = 0; i < num; i++) {
    var yPos = 10*i;
    var numCells = wid/30;

    for(j = 0; j < numCells; j++) {
        blocks[i][j] = 1;
    }                       
}

blocks = new Array();

但是,当我执行代码时,我收到一条错误消息:

can't convert undefined to object

有任何想法吗?:/

4

2 回答 2

4
var blocks = [];
for(i = 0; i < num; i++) {    
    var yPos = 10*i;
    var numCells = wid/30;
    blocks[i] = []; // here is a fix

    for(j = 0; j < numCells; j++) {
        blocks[i][j] = 1;
    }
}
于 2012-12-09T13:30:11.100 回答
0

在您的特定情况下,由于所有行都被初始化为相同(一系列 1),您也可以这样做

var blocks = new Array(),
    blockRow = new Array();
for (var i = 0; i < numCells; i++) {
    blockRow.push(1);
}
for (var i = 0; i < num; i++) {
    blocks.push(blockRow.slice());  // slice() makes a copy of blockRow
}
于 2012-12-09T14:17:39.523 回答