DrillLab
第 18 / 105 道18 / 105 · #280

== 和 === 的区别

What is the difference between == and ===

先自己答,再往下看Answer it yourself first

一句话:===类型不同直接 false==先把两边转成同一类型再比

== 的转换规则很绕,但实际只要记住四条:

  • null == undefinedtrue, 但它们和其他任何值都不 ==(包括 0"")。
  • 数字和字符串比 → 字符串转数字。
  • 布尔参与 → 布尔先转数字true→1,false→0)。 这就是 [] == falsetrue 的原因:[]""0false0
  • 对象和原始值比 → 对象先转原始值。

结论:一律用 ===唯一被普遍接受的 == 用法是x == null—— 一次同时判掉nullundefined

会追问:NaN === NaN?」——falseNaN和自己都不相等。 判断要用 Number.isNaN(x)(别用全局 isNaN,它会先做隐式转换,isNaN("abc")true)。
「有没有更严格的比较?」——Object.is(x, y)。它和 ===只有两处不同:Object.is(NaN, NaN)trueObject.is(0, -0)falseReact 判断 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 == undefined is true, and neither one is == to anything else (not 0, not "").
  • Number against string → the string becomes a number.
  • A boolean involved → the boolean becomes a number (true→1, false→0). That is why [] == false is true: []""0, and false0.
  • 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.

JavaScript为什么别用 ==Why you should not use ==示意Illustrative
10 == "0" // true 字符串转数字
20 == "" // true "" -> 0
30 == false // true false -> 0
4null == undefined // true 特例
5null == 0 // false null 只和 undefined 相等
6[] == false // true [] -> "" -> 0
7NaN == NaN // false 和自己都不相等
8
90 === "0" // false 类型不同,到此为止
10Object.is(NaN, NaN) // true ← React 用它判断 state 变没变
10 == "0" // true the string converts to a number
20 == "" // true "" -> 0
30 == false // true false -> 0
4null == undefined // true a special case
5null == 0 // false null only equals undefined
6[] == false // true [] -> "" -> 0
7NaN == NaN // false not even equal to itself
8
90 === "0" // false different types, so it stops there
10Object.is(NaN, NaN) // true ← React uses this to decide whether state changed