如何更新forEach函数内的变量?获取无法读取未定义

时间:2018-03-16 13:38:51

标签: javascript angular typescript foreach

export class myclass implements OnInit {
    private outagesList;
    private outageArray;

    constructor(private outages: OutagesService){}

    ngOnInit(){
        this.outages.getOutagesList().subscribe((data) => {
            this.outagesList = data;
            this.outagesList.forEach( function (arrayItem)  
            {             
              this.outageArray.push(arrayItem["title"]);          
            });
        )
}

如果我尝试将数据推送到outageArray,则会抛出ERROR TypeError: Cannot read property 'outageArray' of undefined

如何避免此错误?我需要将此outageArray值访问为html。

2 个答案:

答案 0 :(得分:2)

使用箭头功能

this.outagesList.forEach((arrayItem) => {
  this.outageArray.push(arrayItem["title"]);         
});

答案 1 :(得分:-1)

使用post-ES6 Javascript后,forEach等功能可能不是您的最佳解决方案。最简单的方法是使用for..of循环:

this.outages.getOutagesList().subscribe((data) => {
    this.outagesList = data;
    for (let arrayItem of this.outagesList)
    {             
      this.outageArray.push(arrayItem.title);          
    });
)