Cannot read propert "-1" of undefined. Whats this error?


#1

function allRocks(){
let letters = [‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’,‘H’,‘I’,‘J’,‘K’,‘L’,‘M’,‘N’,‘O’,‘P’,‘Q’,‘R’,‘S’,‘T’,‘U’,‘V’,‘W’,‘X’,‘Y’,‘Z’];
let new_list = [];
count = 0;
for (var i of GRID){
count += 1;
for (var j of i){
var coordinate = letters[j] + count.toString();
if (isRock(coordinate)){
new_list.push(coordinate);
}
}
}
return new_list;
}


#2

First off, by investigating this I learned something, so thank you.

This is what I learned about the for loops that you used.

let test = [‘a’,‘b’];

for (let i of test) {
console.log(i);
}
/* output = using ‘of’ gives you the content of each iteration
“a”
“b”
/
for (let i in test) {
console.log(i);
}
/
output = using ‘in’ gives you the index of each iteration
0
1
*/

Your second loop (j of i) is used as an index for ‘letters’ (letters[j]). By using ‘of’ in the for loop it is putting the contents of the cell (eg. letters["^"]), where you want to put the index. using (j in i) gives (eg. letters[2])

Changing that made your code work in my testing.

One other note, unless you are using the variable ‘count’ elsewhere, you should declare ‘count’ with ‘let count=0’, like you do the previous two variables.

Thanks again.


#3

More specific to your question: Cannot read property “-1” of undefined, Whats this error?

Based on what I believe the error to be, it is an out of bounds error for the array ‘letters’. When you try to access letters["^"] for example, the compiler doesn’t know what index that is of array ‘letters’ and cannot give a response.