在 JavaScript 规范中:http://www.ecma-international.org/publications/standards/Ecma-262.htm
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
- If Type(x) is Undefined, return true.
- If Type(x) is Null, return true.
- If Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is -0, return true.
- If x is -0 and y is +0, return true.
- Return false.
- If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
- If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
- Return true if x and y refer to the same object. Otherwise, return false. NOTE This algorithm differs from the SameValue Algorithm (9.12) in its treatment of signed zeroes and NaNs
粗体部分是什么意思?你如何写出一些 JavaScript 来确认它?
我尝试了 alert(typeof(undefined) === 'x');
但它给了我 false
。
最佳答案
在那之前它说:
where
x
andy
are value
所以首先,给 x
和 y
值。
然后忘记“blah”,1 很重要。 x
和 y
必须是同一类型才能通过第 1 步。
第 2 步是“如果 Type(x) 未定义,则返回 true。”。
只有一个值给出未定义类型,undefined
。因此,测试步骤 2 的唯一方法(除了将 undefined
分配给变量):
alert(undefined === undefined)
... 会给出真值。
步骤 3 的工作方式完全相同。唯一的空值是 null
。
alert(null === null)
算法的手动实现会像这样开始:
function equalsequalsequals(x, y)
if (typeof x != typeof y) {
return false;
} else if (typeof x == "undefined") {
return true;
} // …
typeof 运算符无法告诉我们某些内容是否为 null,因此如果不使用 ===
就无法完全实现该算法。但是,由于我们有 ===
,所以我们不需要。
关于Javascript:说明如果 Type(x) 未定义,则返回 true。如果 Type(x) 为 Null,则返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8084470/