简体   繁体   English

Angular 4打字稿:无法读取未定义的属性“列表”

[英]Angular 4 typescript: Cannot read property 'list' of undefined

I'm initializing an array and trying to push elements into the array. 我正在初始化数组,并尝试将元素推入数组。 But I get this error saying Cannot read property 'list' of undefined. 但是我收到此错误消息,提示无法读取未定义的属性“列表”。

list: Array<any> = [];
this.data.forEach(function(element) {
      this.list = [];

    });
    this.data.forEach(function(element) {

        this.list.push({
          'name' : this.url
        })
  });

Even though I'm initializing the array, it is saying as undefined 即使我正在初始化数组,也说是未定义的

use an arrow function to preserve the "this" context like 使用箭头功能保留“ this”上下文,例如

(element) => { } 

instead of 代替

function(element) { } 

arrow functions don't create new scope, regular functions do, so "this" refers to the function scope (where list is undeclared) in a normal function declaration rather than the component scope (where list is declared) like you want. 箭头函数不会创建新作用域,常规函数会创建新作用域,因此“ this”是指常规函数声明中的函数作用域(未声明列表),而不是您想要的组件作用域(声明了列表)。

generally, you will be using arrow functions much more often than not. 通常,您会经常使用箭头功能。 regular function declaration is the more specialized case. 常规函数声明是更专门的情况。

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

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