gpt4 book ai didi

arrays - Angular 5 array.filter 内未定义

转载 作者:行者123 更新时间:2023-12-02 03:42:12 24 4
gpt4 key购买 nike

这是我正在尝试的代码

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

基于条件数的大于、范围、最大值等复杂条件,该函数判断条件是否满足并返回 true 或 false;

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

}
return status;
}

问题是,当我在过滤器内使用 this.checkCondition 时,总是抛出未定义的 checkCondition 属性,这意味着 this 未定义。

我检查了 this 始终未定义,那么如何调用过滤器内的函数?

最佳答案

使用 arrow function这样 this 就会自动正确绑定(bind)。由于您标记了 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);
});
}

另一种方法是使用 bind :

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

关于arrays - Angular 5 array.filter 内未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48195154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com