繁体   English   中英

角度,无法读取未定义的属性“水果”

[英]angular, cannot read property 'fruits' of undefined

在 angular 中,我收到错误:无法读取未定义的属性“水果”。 在我的课堂上,我有:

export class myClass implements OnInit {

fruits: any[];

doSomething() {
this.myArray.forEach(function(m) {
  const my = { test: true };
  this.fruits.push(my);
  }
}

我可能有不同的类型要添加到我的数组中,所以我没有定义接口。 这是什么原因造成的?

如果你想访问它,你应该使用箭头函数:

fruits: any[] = [];

doSomething() {
  this.myArray.forEach(m => {
    const my = { test: true };
    this.fruits.push(my);
  }
}

箭头函数将使其在词法上有界,允许您从对象上下文本身(“外部”范围)访问this 在此处阅读更多相关信息。

你必须初始化水果

export class myClass implements OnInit {

    public myArray: string[] = ['banana', 'Apple, 'Kumquat']
    public fruits: {test: boolean}[] = [];

    constructor() {}

    ngOnInit() {}

    public doSomething(): void {

      let my: any = {}; 

      this.myArray.forEach( m => {
        my = { test: true };
        this.fruits.push(my);
      });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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