1

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? :/

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
MrD
  • 4,986
  • 11
  • 48
  • 90
  • 1
    I suspect you need to declare blocks to be a 2D array. Try [this question][1]. [1]: http://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript – chooban Dec 09 '12 at 13:30

2 Answers2

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;
    }
}
fancyPants
  • 50,732
  • 33
  • 89
  • 96
Michael Malinovskij
  • 1,422
  • 8
  • 22
  • Thank you very much, this fixed it!! ;D Any idea of what was wrong? :) – MrD Dec 09 '12 at 13:33
  • No, just guessed... kidding :) `var blocks = []` - now `blocks` is an `array` but `blocks[i]` is not an array... after adding `blocks[i] = []` it becomes an array and you can manipulate `blocks[i][x]`. Before setting `blocks[i] = []` it was equal to `undefined` and you tryed to change the property of undefined object. I hope it's clear enough, cos my english ins't really good... – Michael Malinovskij Dec 09 '12 at 13:37
  • Oooh ok thanks, got it now ;D Was used to other programming languages where you could just add dimensions without declaring them! – MrD Dec 09 '12 at 13:39
  • 3
    And the second important thing about JS you got to know - blank checkmark near my answer needs to be pressed or arrays could stop work :) – Michael Malinovskij Dec 09 '12 at 13:41
0

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
}
Stuart
  • 9,597
  • 1
  • 21
  • 30