我正在修复一些代码并试图理解正在发生的某个评估。有一个小片段写在 2 个评估应该像这样发生的地方:
const active = true;
const isPerson = true;
const person1Time = null;
const person2Time = null;
// this one is not working as intended
const original = !active && isPerson ? !person1Time : !person2Time;
console.log("original", original);
// fixed when second evaluation is wrapped in parens
const fix = !active && (isPerson ? !person1Time : !person2Time);
console.log("fixed", fix);
通过将三元计算括在括号中,我能够将代码修复为所需的结果。我想知道的是 - 为什么它会这样工作? !active
的计算结果为 false,三元组的计算结果为 true,而 console.log(true && false)
的计算结果为 false。也许我在这里误解了什么。
最佳答案
bool 运算符优先于三元运算符。换句话说,这是:
!active && isPerson ? !person1Time : !person2Time;
等价于:
(!active && isPerson) ? !person1Time : !person2Time;
因此,您会得到不同的结果。
关于javascript - 了解 JavaScript 评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59142095/