typescript - 具有逻辑或的打字稿 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 为真?感谢您的关注,如果这对我来说很明显,对不起。
解决方案
逻辑 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。
推荐阅读
- c++ - 如何在向量中的某个数字之后重新计算进程
- git - git store 如何解决合并后的冲突及其作者历史
- powershell - 在注册表和 gpedit.msc 中启用长文件路径不起作用
- ios - AVSpeechSynthesizer 声音不变
- python - Elasticsearch spark,如何更新时间戳
- java - 错误:java 中的类、接口或枚举预期策略方法
- chromecast - 如何直接从 chromecast 接收器加载元数据?
- django - 如何制作用于将用户重定向到 Django 中输入的地址的表单?
- php - PHP注意问题 - 未定义的索引
- node.js - 为什么我的 Herokuapp 在使用时会闲置并关闭?