Arrays 角度5此未定义的内部array.filter

Arrays 角度5此未定义的内部array.filter,arrays,typescript,filter,angular5,Arrays,Typescript,Filter,Angular5,这是我正在尝试的代码 search(){ this.toDisplay = this.products.filter(function(x){ return this.checkCondition(x.price, condition); } } 它是基于条件数的大于、范围、最大等复杂条件,该函数决定条件是否满足并返回真或假 checkCondition(item, condition){ switch(conditoin){ case 1: ... br

这是我正在尝试的代码

search(){
   this.toDisplay = this.products.filter(function(x){
      return this.checkCondition(x.price, condition);
   }
}
它是基于条件数的大于、范围、最大等复杂条件,该函数决定条件是否满足并返回真或假

checkCondition(item, condition){
  switch(conditoin){
    case 1:  ... brea;
    case 2:  ... brea;
    case 3:  ... brea;

  }
  return status;
}
问题是,当我在过滤器中使用
this.checkCondition
时,总是抛出undefined的
checkCondition
属性,这意味着
this
未定义

我选中了
始终未定义,因此如何调用筛选器内的函数?

使用,以便
自动正确绑定。由于您标记了TypeScript,如果您计划支持仅支持ES5和以下版本的浏览器,则可以传输箭头函数:

search(){
   this.toDisplay = this.products.filter(x => this.checkCondition(x.price, condition));
}
如果不想使用箭头函数,可以捕获
this

search(){
   var selfRef = this;
   this.toDisplay = this.products.filter(function(x) {
      return selfRef.checkCondition(x.price, condition);
   });
}
另一种方法是使用:


另一种方法是将“this”分配给筛选器调用之外的局部变量(人们通常使用“that”或“self”作为标识符)

例如:

search(){
   var that = this;
   this.toDisplay = this.products.filter(function(x){
      return that.checkCondition(x.price, condition);
   }
}

箭头功能仍然不受所有浏览器的支持,特别是在不同的设备上,感谢您的帮助reply@AliAdravi既然您使用的是TypeScript,那么实际上您不必担心;arrow函数将自动传输到支持的任何内容。伙计,你让我开心,我总是害怕在键入脚本中使用arrow函数,非常感谢这一点。实际上,在你发布的同时,我在我的答案中添加了这个作为编辑。如果不能使用箭头函数,这绝对是一个很好的解决方案。不过,您应该添加一个示例。
search(){
   var that = this;
   this.toDisplay = this.products.filter(function(x){
      return that.checkCondition(x.price, condition);
   }
}