提问人:OneClutteredMind 提问时间:12/1/2021 更新时间:12/1/2021 访问量:480
Javascript 布尔逻辑(将双爆炸与真值/假值进行比较)
Javascript boolean logic (comparing double bang with truthy/falsy values)
问:
我正在检查一些代码,我发现了一些我想由 Javascript 老手运行的东西。我对 Javascript 感觉很舒服,但我总是设法遇到一些让我说,“我不知道 Javascript !
我希望这是其中一种情况:
if (this.props.referralId != prevProps.referralId ||
this.props.referralValidationStatus != prevProps.referralValidationStatus ||
this.props.customerName != prevProps.customerName &&
!!prevProps.personId != !this.props.personId) {
// perform whatever logic is here...
}
我的问题:
- JS知道如何自动识别||和 &&?或者这段代码是否缺少括号 ||比较?
- 正如这里所解释的那样,这是否公平,在将布尔值与真值/假值进行比较时,我是否应该期待明显的行为?
我对这里的逻辑应该是什么感到困惑。如果我要重写它,我会这样做:
if ((this.props.referralId !== prevProps.referralId ||
this.props.referralValidationStatus !== prevProps.referralValidationStatus ||
this.props.customerName !== prevProps.customerName)
&& (!!prevProps.personId === !!this.props.personId)) {
// Perform logic
}
但是,我想确认并确保我没有遗漏我可能错过的有关 JS 的内容。
提前感谢您确认我的预感或在 JS 方面对我进行新知识的教育。期待您的评论和/或回答。
答:
2赞
Rafael Odon
12/1/2021
#1
像大多数语言一样,Javascript 中有一个优先规则。 如前所述,之前进行了评估 此处.所以,如果你需要检查所有,然后使用最终结果来制作,你是对的!使用括号。
&&
||
ors
and
你对重构也是对的:
!!
!!prevProps.personId != !this.props.personId
等同于:
!!prevProps.personId === !!this.props.personId
换句话说,它正在检查两者是否都具有某个值(作为布尔值计算为 True),或者是否两者都为空/未定义/Nan(计算结果为 False 作为布尔值)。prevProps.personId
this.props.personId
评论
0赞
OneClutteredMind
12/1/2021
我今天学到了一些东西......我不知道&&之前被评估过||。谢谢你的提示!
0赞
Michael Abeln
12/1/2021
#2
第一条语句说(伪代码):
if (
//the first statement returns truthy
this.props.referralId != prevProps.referralId ||
// or the second statement returns truthy
this.props.referralValidationStatus != prevProps.referralValidationStatus ||
// or the combination of the third and fourth statements returns truthy
this.props.customerName != prevProps.customerName
&&
!!prevProps.personId != !this.props.personId
)
// then...
{
// perform whatever logic is here
}
您的重写版本说(伪代码):
if (
// one of these three statements is truthy
(this.props.referralId !== prevProps.referralId ||
this.props.referralValidationStatus !== prevProps.referralValidationStatus ||
this.props.customerName !== prevProps.customerName)
&& // AND!
// this statement also evaluates truthy
(!!prevProps.personId === !!this.props.personId)
)
// then...
{
// perform whatever logic is here
}
希望这能解释代码块之间的差异。
否则@rafaelodon是正确的
评论
!!