2

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!

1 Answer 1

2

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

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

2 Comments

please click accept, if it solves your problem, thanks
yep, i didnt realize i flipped the x and y indexes. thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.