JavaScript 中的严格相等比较 ( === )

Strict Equality Comparison ( === ) in JavaScript

=== 运算符不进行隐式类型转换,因此即使值相等但类型不同 === 也只会 return false。

严格相等比较时,先进行什么操作?喜欢:

  1. 它首先检查左侧操作数和右侧操作数的数据类型

    5 === '5' // Return false as, number !== string

  2. 先比较两个操作数的值,然后再检查两个操作数的数据类型。

    5 === 5 // Return true as, 5 === 5 (Both value is same)

    现在会检查数据类型吗?

  1. 检查===的第一步是"Are the types of the operands the same?"。如果答案为 "no",则不会进行进一步检查,结果为 false.

  2. 其次,如果类型相同,它的作用与==完全相同,这意味着检查值是否相等。

来自mozilla docs

Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal. Otherwise, if the values have the same type and are not numbers, they're considered equal if they have the same value. Finally, if both values are numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0.

因此,=== 运算符首先检查类型,如果它们相等,则检查它们的值。如果值相同,则 returns 为真,否则为 returns 假。如果类型不匹配,则 returns false 根本不检查值。