This problem is from code signal and I solved it, The first solution entered worked but I want to know why the second doesn´t.
I am supposed to write a function that takes a matrix as an input and returns a sum of items that are not below a 0.
Here is an example of the matrix.
matrix = [[1, 1, 1, 0],
[0, 5, 0, 1],
[2, 1, 3, 10]]
the output should be
solution(matrix) = 9
function solution(matrix) {
let sum =0
for(j=0;j<matrix[0].length;j++){
for(let i=0;i<matrix.length;i++){
if(matrix[i][j]==0){
break
}
else{
sum += matrix[i][j]
}
}
}
return sum
}
this works but this other one has an error
function solution(matrix) {
let sum =0
for(j=0;j<matrix[j].length;j++){
for(let i=0;i<matrix.length;i++){
if(matrix[i][j]==0){
break
}
else{
sum += matrix[i][j]
}
}
}
return sum
}
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at solution (<anonymous>:5:25)
at <anonymous>:1:13
The problem is using the the variable as an index for the columns
I just want to know why the later did not work in order to learn