J4yd3n222
J4yd3n222

Reputation: 23

Seemingly random TypeError in JavaScript

Currently, I'm working on a small minigame that would work in a website, but I've managed to hit a rather strange TypeError pretty early on. Here's the code I'm currently working with:

level0 = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]];

let character = {
    x: 0,
    y: 0,
}

function setBoard(array2d) {
let i;
let m = 0;
for(i = 0; i < (array2d.length * 10); i++) {
    if (m == 6) {
        break;
    };
    let z = document.getElementById(`${String(m)}-${i}`).classList;
    // let z1 = `${m}-${i} is ${z}`;
    // console.log(z1);
    if (z == "noselect wall") {
        array2d[m][i] = 1;
    } else if (z == "noselect gameboard character") {
        array2d[m][i] = 2;
        character.x = i;
        character.y = m;
        document.getElementById(`${String(m)}-${i}`).innerHTML = "YOU";
    } else if (z == "noselect gameboard goal") {
        array2d[m][i] = 3;
        document.getElementById(`${String(m)}-${i}`).innerHTML = "GOAL";
    }

    if (i == 9) {
        m++;
        i = -1
    }
}
}
setBoard(level0);
console.log(character);
console.log(level0[character.x + 1][character.y]);

function moveRight(array2d) {
    if (array2d[character.x + 1][character.y] == 0) {
        character.x++;
        console.log(character);
    }
}

And here's the error: Uncaught TypeError: Cannot read property '3' of undefined at script.js:43 I've checked that the properties are stored as numbers, and they seem to log as numbers. I've also made sure this is strictly a JavaScript problem, as no HTML seems to be functioning incorrectly at any point throughout this process. Is there something I'm missing? Any help will be appreciated!

Upvotes: 2

Views: 85

Answers (1)

Eason Yu
Eason Yu

Reputation: 329

as you can see, index m represent outer index, i represent the inner

array2d[m][i] = 2; character.x = i; character.y = m;

however, this console.log statement use i(character.x) as outer,which will be more than 6 to make it undefined

console.log(level0[character.x + 1][character.y]);

then undefined[m] will be uncaught type error

Upvotes: 2

Related Questions