首页 > 解决方案 > array.find 函数阻止访问父类 'this' 对象

问题描述

我在一个角度组件中有这个功能。一旦我尝试查询“myData.Order3”数组,我就无法从“find”函数中访问“this”。'this' 报告为未定义,而在父函数中对 'this' 的其他引用很好。

这显然是一个范围界定问题,但在修复它时遇到了问题。

public toggle():void {
    this.freq.toggle();
    this.checkState().subscribe(response => {
        console.log(this.freq.frequency);
        this.myData = response as ArrayCast;
        if (this.myData.Order3.find(function(ele) {
            return ele == this.freq.frequency; // <= "this" reports as undefined
        })){
                this.toggleStyle="ui-button-danger";
        }
        console.log(this.myData);
    });
}

标签: angulartypescriptscope

解决方案


使用 Lambda 表达式=>而不是function

if (this.myData.Order3.find((ele) => ele === this.freq.frequency))

推荐阅读