为什么我无法读取未定义的属性“ 0”?

恐龙

我正在尝试解决一个挑战,但是当我访问二维数组时,出现错误:

无法读取未定义的属性“ 0”。

我试图通过添加参数的默认值来解决,但是它没有用。

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);

dbramwell

当i = 1且idx =(matrix.length-1)时,您将得到未定义的matrix [matrix.length]。您可以通过添加以下内容的简单检查来解决此问题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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

NPM无法读取未定义的属性“ 0”

Javascript Uncaught TypeError:无法读取未定义的属性“ 0”

为什么TypeError:无法读取未定义的属性“ 0”?

Ionic InfiniteScroll:TypeError:无法读取未定义的属性“ 0”

无法读取未定义的属性0

JavaScript测验TypeError:无法读取未定义的属性“ 0”

角度:无法读取未定义的属性“ 0”

为什么在生产版本中使用ng2-bootstrap-modal时出现此错误-'无法读取未定义的属性'0'?

React Native无法读取未定义的属性“ 0”

无法读取角度6中未定义的属性“ 0”

ReactJS-TypeError:无法读取未定义的属性“ 0”

Nativescript Vue TypeError:无法读取未定义的属性“ 0”

TypeError:无法读取未定义的CryptoJS的属性“ 0”

无法读取未定义JSON的属性“ 0”

无法读取未定义的属性“ 0”-JavaScript

$ .getJSON,无法读取未定义的属性“ 0”

未捕获的TypeError:无法读取未定义的属性“ 0”

未捕获的TypeError:无法读取未定义的属性“ 0”

For循环:TypeError:无法读取未定义的属性“ 0”

为什么我会收到Uncaught TypeError:无法在分配时读取未定义的属性“ 0”?

收到此错误:无法读取未定义的属性“0”

类型错误:无法读取未定义值的属性“0”。标题 [0]

无法读取文件上传的未定义属性“0”

类型错误,无法读取未定义的属性 0

Angular TypeError:使用 event.target.file[0] 时无法读取未定义的属性“0”

AWS Lambda:“无法读取未定义的属性‘0’”

React js 错误:无法读取未定义的属性“0”

React TypeError:无法读取未定义的属性“0”

获取“TypeError:无法读取未定义的属性”,但是当我 console.log 时我得到 0 个未定义的值