Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript TypeError:在成员数组上使用forEach时“这是未定义的”_Javascript_Angular_Typescript - Fatal编程技术网

Javascript TypeError:在成员数组上使用forEach时“这是未定义的”

Javascript TypeError:在成员数组上使用forEach时“这是未定义的”,javascript,angular,typescript,Javascript,Angular,Typescript,我有一个类marketData: 但是,上面给出了一个错误类型ERROR:这是未定义的。我以这种方式检查itemPrices时遇到了完全相同的错误: this.itemPrices.forEach(function(prices){ if(prices.length != this.itemCount){ // handle error }); i、 e.在功能参数中没有此选项 访问itemCount成员变量的正确方法是什么?

我有一个类marketData:

但是,上面给出了一个错误类型ERROR:这是未定义的。我以这种方式检查itemPrices时遇到了完全相同的错误:

this.itemPrices.forEach(function(prices){
          if(prices.length != this.itemCount){
              // handle error
          });
i、 e.在功能参数中没有此选项

访问itemCount成员变量的正确方法是什么?

函数中的值与类中的值不同。可以使用fat arrow函数或bindthis将函数绑定到类

this.itemPrices.forEach(function(prices){
          if(prices.length != this.itemCount){
              // handle error
          }).bind(this);

这是因为你们使用forEach的方式。用下面的方法代替。建议在使用typescript类时始终使用箭头函数,否则您将继续遇到此问题

this.itemPrices.forEach((prices) =>{
          if(prices.length != this.itemCount){
              // handle error
            }
});
您可以使用ES6访问此文件。无论如何,当涉及到JavaScript并在JS中的OOP中使用它们时,一定要读到udnerstand的上下文

this.itemPrices.forEach((prices: number) => {
  if (prices.length != this.itemCount){
    // handle error 
  });
});
this.itemPrices.forEach((prices) =>{
          if(prices.length != this.itemCount){
              // handle error
            }
});
this.itemPrices.forEach((prices: number) => {
  if (prices.length != this.itemCount){
    // handle error 
  });
});