0

I am trying to go through the maze on html canvas with values. I have created a 2d array with values in it.

const pot=[[0, 2], [-2, 0], [0, 1], [-1, 0], [0, 2], 
    [1, 0], [0, 3], [1, 0], [0, 1], [1, 0], 
    [0, -1], [2, 0], [0, -1], [1, 0], [0, 1], 
    [4, 0], [0, -1], [-3, 0], [0, -1], [3, 0], 
    [0, -2], [2, 0], [0, 3], [-1, 0], [0, 1], 
    [1, 0], [0, 1], [-1, 0], [0, 1], [-1, 0], 
    [0, -1], [-6, 0], [0, 2], [1, 0], [0, 2], 
    [1, 0], [0, 1], [-1, 0], [0, -1], [-1, 0], 
    [0, -2], [-1, 0], [0, 1], [-5, 0], [0, -1], 
    [1, 0], [0, -1], [-1, 0], [0, -1], [2, 0], 
    [0, -1], [-1, 0], [0, -1], [-2, 0], [0, 4], 
    [-2, 0], [0, -1], [1, 0], [0, -1], [-2, 0], 
    [0, 3], [2, 0], [0, 2], [-1, 0], [0, -1], 
    [-1, 0], [0, 2], [3, 0], [0, -2], [2, 0], 
    [0, 1], [-1, 0], [0, 3], [-1, 0], [0, 1], 
    [4, 0], [0, -1], [-2, 0], [0, -1], [5, 0], 
    [0, 1], [-2, 0], [0, 1], [2, 0], [0, 1]];

to read values from it, i made a for loop

var dolz=pot.length;
    for(var i=0; i<=dolz; i++){
        x += pot[i][0]*(w/dimenzija);
        y += pot[i][1]*(h/dimenzija);
        ctx.lineTo(x, y);
    }
    ctx.stroke();

When I run the code, I get an error Uncaught TypeError: Cannot read property '0' of undefined that refferes to the jquery library which then refferes back to the for loop code and points the error at the x += pot[i][0]*(w/dimenzija); part of the code. What could be the reason of this error?

1
  • Remove the = from <=. Consider this array [1, 2, 3]. The length is 3, but it's indicies are 0, 1, 2. So if you're iterating less than or equal to the length, there is no index 3, thus the value is undefined and it in turn (in your case) has no index of 0 Commented Feb 26, 2020 at 20:21

1 Answer 1

2

Change the ‘<=‘ to ‘<‘. Length of an array is always greater than the last index in an array.

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

Comments

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.