0

i'm new to javascript and i'm developing tetris game. i have written some piece of code and reused some code from other sites. But one of the function is causing me some problems and i'm getting an error as "undefined is not an object evaluating board[y][x]". The piece of code is pasted below:

var COLS=10, ROWS=20;
var board = [];
function run() {
ctx.clearRect( 0, 0, canvas.width, canvas.height );

ctx.strokeStyle = 'black';
for ( var x = 0; x < COLS; ++x ) {
    for ( var y = 0; y < ROWS; ++y ) {
        if ( board[ y ][ x ] ) {
            ctx.fillStyle = colors[ board[ y ][ x ] - 1 ];
            drawBlock( x, y );
        }
    }
}
}

i'm not understanding as why am i getting the error. i have tried executing it in both safari and IE 11 but the result is the same. i even tried using the typeof keyword in the if statement but there's no change. Could anyone please help me to get rid of this error.

thanks

3
  • 1
    You've initialized "board" as [], but you're using it as if it's an array of objects (or arrays). Where is the code that puts values in the "board" array? Commented Nov 16, 2014 at 19:48
  • are you meaning board[y][x] to be board[x][y] Commented Nov 16, 2014 at 19:53
  • You need to check that the 1st dimension is not empty, as well. Change your condition to board[y] && board[y][x] to get at what you expected Commented Nov 16, 2014 at 20:04

1 Answer 1

1

You cannot do board[ y ][ x ] if you haven't initialised the board variable properly. You are trying to execute next line:

board [0][0]

and what javascript would do, is, first it will try to get board[0] which will be undefined, then it will try to do undefined[0], which will fire the error:

undefined is not an object

You should first put some data into your board array, before running that loop.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.