类型错误:无法读取未定义的属性(读取“_matrix”)

问题描述 投票:0回答:1

我想从图块的节点列表中写下我在棋盘(跳棋)上的图形位置。我定义了一个二维数组并用 0 填充它。如果我在方法开始处使用

this._matrix[0][1] = 1;
,我可以自由更改该值。但是,当在 forEach 数组内更改它时,我收到此类错误。

how it is supposed to finally be

我的代码:

class Game{
    _matrix = Array(8).fill().map(() => Array(8).fill(0));
    _board = document.querySelectorAll("div.container>div"); // all tiles

    constructor(blackTiles){
        this.blackTiles = blackTiles;
    }
    
    fillMatrix(){
        console.log(this._matrix[0][1]) // 0
        this._matrix[0][1] = 1 // no errors
        console.log(this._matrix[0][1]) // 1

        this._board.forEach(function(element, i){
            if(i < 8){
                if(element.classList.contains("infest")){ //tiles, that have figures, have class "infest"
                    try{
                        let row = i / 8;
                        let col = i % 8;
                        this._matrix[parseInt(row)][parseInt(col)] = 1; //error
                    } catch(Error) { console.error(Error); }
                }
                i++;
            }
        });

        return this._matrix;
    }
}

完整错误:

TypeError: Cannot read properties of undefined (reading '_matrix')
    at script.js:41:30
    at NodeList.forEach (<anonymous>)
    at Game.fillMatrix (script.js:35:21)
    at window.onload (script.js:102:22)
javascript multidimensional-array foreach
1个回答
0
投票

正如您正确发现的那样,问题出在该特定行上。

这是因为在函数内部(用

function(){}
定义),
this
指的是函数本身,而不是包含的上下文。

此时您有三个选择。

  1. 制作并使用对
    this
    的引用:
const _this = this;
list.forEach(function(){
    _this.something;
})
  1. 将函数绑定到当前对象:
list.forEach((function(){
    this.something;
}).bind(this));
  1. 使用箭头功能;它会自动绑定到调用者:
list.forEach(() => {
    this.something;
});
  1. 奖励点:如果您使用类,您也可以使用私有 lambda 属性来执行此操作:
_handleSomething = () => {
    this.something;
}

list.forEach(this._handleSomething);

```js
© www.soinside.com 2019 - 2024. All rights reserved.