== 和 === 的区别
What is the difference between == and ===
一句话:===类型不同直接 false;== 会先把两边转成同一类型再比。
== 的转换规则很绕,但实际只要记住四条:
null == undefined是true, 但它们和其他任何值都不==(包括0和"")。- 数字和字符串比 → 字符串转数字。
- 布尔参与 → 布尔先转数字(
true→1,false→0)。 这就是[] == false为true的原因:[]→""→0,false→0。 - 对象和原始值比 → 对象先转原始值。
结论:一律用 ===。唯一被普遍接受的 == 用法是x == null—— 一次同时判掉null 和 undefined。
会追问:「NaN === NaN?」——false,NaN和自己都不相等。 判断要用 Number.isNaN(x)(别用全局 isNaN,它会先做隐式转换,isNaN("abc") 是 true)。
「有没有更严格的比较?」——Object.is(x, y)。它和 ===只有两处不同:Object.is(NaN, NaN) 是 true,Object.is(0, -0) 是 false。React 判断 state 变没变用的就是它。
In one line: === returns false straight away when the types differ; == converts both sides to one type first, then compares.
The == conversion rules are convoluted, but four points cover practice:
null == undefinedistrue, and neither one is==to anything else (not0, not"").- Number against string → the string becomes a number.
- A boolean involved → the boolean becomes a number (
true→1,false→0). That is why[] == falseistrue:[]→""→0, andfalse→0. - Object against primitive → the object becomes a primitive.
The conclusion: use === everywhere. The one == that everybody accepts is x == null — it rules out null and undefined in a single check.
Follow-up: “NaN === NaN?” — false. NaN is not even equal to itself. Test it with Number.isNaN(x) — not the global isNaN, which coerces first, so isNaN("abc") is true.
“Is there anything stricter?” — Object.is(x, y). It differs from === in exactly two places: Object.is(NaN, NaN) is true, and Object.is(0, -0) is false. This is what React uses to decide whether state changed.