简体   繁体   中英

Why I'm getting Cannot read property '0' of undefine?

I'm trying to solve a challenge,but when I access to a two dimensional array, I get an error:

Cannot read property '0' of undefined.

I have tried to solved by add default value of argument, but it did not work.

 function minesweeper(matrix= [[]]) { let res = []; for(let i=0;i<matrix.length;i++){ let temp = []; for(let j=0;j<matrix.length;j++){ temp.push( count(i,j,matrix) ) } res.push(temp); } console.log(res); } function count(idx, jdx, matrix = []){ let count = 0; for(let i=-1;i<=1;i++){ if(i + idx < 0) continue; for(let j=-1;j<=1;j++){ if( jdx + j < 0 || (i == 0 && j == 0)) continue; if(matrix[i+idx][j+jdx] == true) count += 1; // this line } } return count; } let matrix = [[true, false, false], [false, true, false], [false, false, false]]; minesweeper(matrix); 

When i = 1 and idx = (matrix.length - 1) you end up with matrix[matrix.length] which is undefined. You can fix this by adding a simple check for matrix[i+idx] :

 function minesweeper(matrix= [[]]) { let res = []; for(let i=0;i<matrix.length;i++){ let temp = []; for(let j=0;j<matrix.length;j++){ temp.push( count(i,j,matrix) ) } res.push(temp); } console.log(res); } function count(idx, jdx, matrix = []){ let count = 0; for(let i=-1;i<=1;i++){ if(i + idx < 0) continue; for(let j=-1;j<=1;j++){ if( jdx + j < 0 || (i == 0 && j == 0)) continue; if(matrix[i+idx] && matrix[i+idx][j+jdx] == true) count += 1; // this line } } return count; } let matrix = [[true, false, false], [false, true, false], [false, false, false]]; minesweeper(matrix); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM