Javascript无法将undefined转换为object

时间:2012-12-09 13:27:32

标签: javascript

我有以下代码

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

有什么想法吗? :/

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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
}