HiSulu
HiSulu

Reputation: 49

JavaScript Reading Array - Cannot read property '0' of undefined

when I run the code below I get an error in the browser console which reads: Uncaught TypeError: Cannot read property '0' of undefined

The code does print what I intended though I am curious to the nature of the error. I have pasted the output at the bottom of this post.

var chessBoard = [];
for(let i = 0; i < 8; i++) {
   chessBoard[i] = [];
   for(let j = 0; j < 8; j++) {
   chessBoard[i][j] = (i + j)% 2 === 0 ? 'Black' : 'White';
}} // populate a 2 dimensional array with colors representing a chess board.

for(let i = 7; i => 0; i--) {
    let str_horizontal = '';
    for (let j = 0; j < 8; j++) {
        str_horizontal += chessBoard[i][j];
    }
    console.log(str_horizontal);
}

WhiteBlackWhiteBlackWhiteBlackWhiteBlack VM116:13 BlackWhiteBlackWhiteBlackWhiteBlackWhite VM116:13 WhiteBlackWhiteBlackWhiteBlackWhiteBlack VM116:13 BlackWhiteBlackWhiteBlackWhiteBlackWhite VM116:13 WhiteBlackWhiteBlackWhiteBlackWhiteBlack VM116:13 BlackWhiteBlackWhiteBlackWhiteBlackWhite VM116:13 WhiteBlackWhiteBlackWhiteBlackWhiteBlack VM116:13 BlackWhiteBlackWhiteBlackWhiteBlackWhite VM116:11

Uncaught TypeError: Cannot read property '0' of undefined at :11:40

I have been struggling with this a while now and have made little progress. I cannot see the problem. I appreciate any help, Thanks.

Upvotes: 0

Views: 1460

Answers (1)

Abslen Char
Abslen Char

Reputation: 3135

In your for loop you're using an arrow function , instead of => put >=

var chessBoard = [];
for(let i = 0; i < 8; i++) {
   chessBoard[i] = [];
   for(let j = 0; j < 8; j++) {
   chessBoard[i][j] = (i + j)% 2 === 0 ? 'Black' : 'White';
}} // populate a 2 dimensional array with colors representing a chess board.

for(let i = 7; i >= 0; i--) {
    let str_horizontal = '';
    for (let j = 0; j < 8; j++) {
        str_horizontal += chessBoard[i][j];
    }
    console.log(str_horizontal);
}

Upvotes: 3

Related Questions