缺少参数 &&&||括号中的运算符,但仍在工作

argument missing && || operators in parenthesis but still working

本文关键字:amp 工作 运算符 参数      更新时间:2023-09-26

我遇到过这段代码,其中if语句包含一个没有&&和/或||运算符的参数。

if (event.target.scrollTop > 0 !== isViewScrolled) {
    //do something
}

这怎么可能呢?括号中包含的逻辑是什么?

(event.target.scrollTop > 0返回一个布尔值,所以javascript只检查这个布尔值是否等于isViewScrolled

检查运算符优先级 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

根据上述>(大于(的优先级高于!=(不等式(,因此

event.target.scrollTop > 0 !== isViewScrolled

相当于

(event.target.scrollTop > 0) !== isViewScrolled

尽管两者是等效的,但最好在评估顺序不明确的地方包含括号。