JS中if(x <= 100)与if(!(x > 100))为何不等?特殊值有哪些?
if(x <= 100) and if(!(x > 100)) Aren't Equivalent in JavaScript Great question! This discrepancy boils down to how JavaScript handles NaN (Not-a-Number) and implicit type conversion in comparison operations. Let's break this down step by step.
The Root Cause: NaN's Unique Behavior
In JavaScript, NaN has a weird but well-defined rule: it never equals any value (including itself), and all comparisons with NaN return false.
Let's test this logic against both conditions:
- For
x <= 100: IfxisNaN, this comparison returnsfalse(sinceNaN <= 100evaluates to false). - For
!(x > 100): IfxisNaN,x > 100first returnsfalse(again, all comparisons with NaN fail), then the negation!falseresolves totrue.
That’s the core reason the two conditions behave differently when x resolves to NaN during comparison.
Special Values That Trigger This Difference
Any value that gets converted to NaN when evaluated in a numeric comparison will cause this mismatch. Here are the most common culprits:
- The literal
NaNitself undefined(sinceNumber(undefined)returnsNaN)- Non-numeric strings that can’t be parsed as valid numbers, e.g.,
"abc","123xyz","$50" - Plain objects (like
{}) — when compared to a number, they convert to the string"[object Object]", which becomesNaNwhen coerced to a number
Example Code to Verify
Let’s run test cases to see this behavior in action:
// Test with NaN const x1 = NaN; console.log(x1 <= 100); // false console.log(!(x1 > 100)); // true // Test with undefined const x2 = undefined; console.log(x2 <= 100); // false console.log(!(x2 > 100)); // true // Test with non-numeric string const x3 = "hello"; console.log(x3 <= 100); // false console.log(!(x3 > 100)); // true // Test with plain object const x4 = {}; console.log(x4 <= 100); // false console.log(!(x4 > 100)); // true
Key Takeaway
When writing conditional logic in JavaScript, always be mindful of implicit type conversion and NaN's quirky behavior. If you expect x to be a number, validate it first (using Number.isNaN() or typeof x === 'number' && !isNaN(x)) before making comparisons to avoid unexpected bugs.
内容的提问来源于stack exchange,提问作者Src

