首页 > 解决方案 > 具有逻辑或的打字稿 lambda 函数

问题描述

很抱歉用一些可能认为简单的语法来提出这个问题,但我无法理解 this.One => this.IsWeird

所以我有一些代码:

get items(): readonly TodoItem[] {
    return this.list.items.filter(item => this.showComplete || !item.complete);
} 

showComplete: boolean = false;

显然这相当于:

get items(): readonly TodoItem[] {
   if (this.showComplete == true) {
       return this.list.items;
   }

   if (this.showComplete == false) {
       return this.list.items.filter(item => !item.complete);
   }  
} 

showComplete: boolean = false;

'||' lambda 函数中的运算符让我很失望。如果我想让相反的情况发生,我会使用什么运算符,比如如果我想返回未完成的项目,如果 showComplete 为真?感谢您的关注,如果这对我来说很明显,对不起。

标签: typescript

解决方案


逻辑 OR 运算符a || b可用作 JavaScript 中if a is not true, evaluate b. 它是由于短路评估而起作用的,这意味着如果a为真,则不需要评估表达式的其余部分,因为它无关紧要,无论如何,表达式都会为真。但是,如果a为 false,它将执行b以完全评估表达式。

在该.filter()方法中,如果this.showComplete为真,它将为每个条目返回真(即它只会评估this.showComplete)。如果this.showComplete为假,它将评估整个表达式并返回!item.complete

要更改响应以按照您的要求执行相反的操作,您可以将其更改为:

return this.list.items.filter(item => this.showComplete && !item.complete);

a && b也是 JavaScript 中if a is true, evaluate b. 所以在这种情况下,当this.showComplete为真时,表达式的第二部分也将被计算。当this.showComplete为 false 时,不会返回任何内容,因为每个评估都将返回 false。


推荐阅读