对于`x <y && y> x`有什么理由吗?

Rum*_*mps 10 javascript boolean-expression logical-operators

我正在浏览一些用于验证表单条目的Javascript代码,我注意到了一个if读取的语句if (!(x < y && y > x)) {...}

我最初的想法是,这种重言式结构完全是多余的,应该放弃两个比较中的一个.万一有机会我错了,但事实上还有更多,我想我会问.

我的另一个想法是,它可能是另一种语言所必需的一些成语的例子,程序员在这里只是习惯性地将它们带到Javascript中(虽然我会惊讶地发现这样的语言是必需的,也用于任何类型的环境).

编辑

特定代码的功能是测试提交事件的开始和结束日期是否可能(即结束日期是在开始日期之后).实际的例子读取if(!(start_time < end_time && end_time > start_time)) {...}其中两个start_timeend_timeDateTime值.

编辑2

不是这个问题的重复,因为在这种情况下,问题是需要测试在if声明中看起来相互包含的两个条件,而在这种情况下,问题是如何使if声明解决似乎需要两个相互排斥的条件是同时是真的.

Nin*_*olz 5

它看起来像一个允许伪值的模式,它转换为一个数字(没有NaN,像''null).

function f(x, y) {
    return [!(x > y && y < x), x <= y, x < y || x === y].join(' ');
}

console.log(f(1, 2));                 //  true
console.log(f(2, 1));                 // false
console.log(f(1, 1));                 //  true
console.log(f('', 1));                //  true
console.log(f(1, ''));                // false
console.log(f('', ''));               //  true
console.log(f(undefined, undefined)); //  true \
console.log(f(1, undefined));         //  true  different values by using other comparisons
console.log(f(undefined, 1));         //  true /
console.log(f(null, null));           //  true
console.log(f(1, null));              // false
console.log(f(null, 1));              //  true
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)