admin管理员组

文章数量:1418621

I have the following code

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

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

With

blocks = new Array();

However, when I execute the code I receive an error stating that:

can't convert undefined to object

Any ideas? :/

I have the following code

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

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

With

blocks = new Array();

However, when I execute the code I receive an error stating that:

can't convert undefined to object

Any ideas? :/

Share Improve this question edited Dec 9, 2012 at 13:30 Henrik Aasted Sørensen 7,16711 gold badges54 silver badges64 bronze badges asked Dec 9, 2012 at 13:27 MrDMrD 5,08412 gold badges54 silver badges95 bronze badges 1
  • 1 I suspect you need to declare blocks to be a 2D array. Try [this question][1]. [1]: stackoverflow./questions/966225/… – chooban Commented Dec 9, 2012 at 13:30
Add a ment  | 

2 Answers 2

Reset to default 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;
    }
}

In your particular case, since all the rows are initialised to be the same (a series of 1s), you can also do

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
}

本文标签: Javascript can39t convert undefined to objectStack Overflow