0

i am using the p5js libary and ran into a problem that i have never had before. I have a function called neighbors with the constructor neighbors(x, y). I call that function multiple times each loop (2500 times). If i use this code:

if(x < 50){
    if(spots[1][1]){
        neighborCount++;
    }
}

nothing goes wrong. As soon as i replace the code with this:

if(x < 50){
    if(spots[parseInt(x+1)][1]){
        neighborCount = 3;
    }
}

I get an error in the console:

TypeError: spots[(x + 1)] is undefined

I tried using

spots[parseInt(x+1)][1]

but that only changed the error to

TypeError: spots[parseInt(...)] is undefined

I hope i explained my problem well enough and you can understand it. If i forgot something please tell me i will add it as soon as possible.

Thanks in advance

FritzFurtz

5
  • 1
    What is x? And why do you use parseInt on what appears to be a number? Commented Mar 23, 2017 at 14:34
  • What is spots? Does it contain that many items? Commented Mar 23, 2017 at 14:36
  • i think spots length less than x+1 Commented Mar 23, 2017 at 14:36
  • x is a number between 0 and 49. Oh i think i just found my mistake. I check if x < 50 but it is always smaller 50. Let me check that now. Oh yes. Array 0 indexing... Thanks for asking questions, that always help :) Commented Mar 23, 2017 at 14:37
  • but x+1 when x=49 => x+1=50 its out of range Commented Mar 23, 2017 at 14:37

2 Answers 2

1

I did a classic mistake: 0 indexing in arrays. The if(x < 50) was supposed to check if it is undefinded, because the array size is 50. But i forgot that the last value is indexed 49 so i have to check if(x < 49). Thank you guys for always answering fast!

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

2 Comments

I don't get it.
I access x+1. If i do that i have to check that x + 1 is not undefined and for that i made a if(x < 50), because the array size is 50. But since arrays are 0 indexed, i had to make a if(x < 49) so that x + 1 can be max. 49
0

try with this

if(x < 50){
    if(spots[parseInt(x,10)+1][1]){
        neighborCount = 3;
    }
}

1 Comment

TypeError: spots[(parseInt(...) + 1)] is undefined. Thanks for the fast answer anyway :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.