When compiling my code I get an error of
TypeError: Cannot read property '0' of undefined
I understand that the error essentially means the code is trying to pull an array element that doesn't exist. This usually happens because there is a for loop incrementation without any bounds to terminate. However, across++ has a bound of for(let across=0; across<matrix[0].length; across++){
I would like to know what is causing the error message.
Context/Task:
After becoming famous, the CodeBots decided to move into a new building together. Each of the rooms has a different cost, and some of them are free, but there's a rumour that all the free rooms are haunted! Since the CodeBots are quite superstitious, they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms. Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0). Example: matrix =
[[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]the output should be solution(matrix) = 9.
function solution(matrix) {
let count = 0;
for(let across=0; across<matrix[0].length; across++){
for(let down=0; down<matrix.length; down++){
if(matrix[across][down] == 0){
across++;
}else{
count += matrix[across][down];
}
}
}
return count;
}
//[ [1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10] ]
// 0 1 2
To summarize, you have accidentally transposed row and column in your array access. Change the various array access code to:
matrix[down][across]
Notes on debugging this: the error message suggested that where you use matrix[across][down], it must have been the case that matrix[across] had value undefined and down had the value 0. That's what caused the error:
TypeError: Cannot read property '0' of undefined
And that happened because across was out of range. JavaScript doesn't do range checking and simply yields undefined in that case. If your matrix happened to have 3 rows and 3 columns, you wouldn't have seen the error (though it would have been there, waiting to fail in future).