Javascript:说明如果 Type(x) 未定义,则返回 true。如果 Type(x) 为 Null,则返回 true

标签 javascript

在 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:

  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is Number, then
    1. If x is NaN, return false.
    2. If y is NaN, return false.
    3. If x is the same Number value as y, return true.
    4. If x is +0 and y is -0, return true.
    5. If x is -0 and y is +0, return true.
    6. Return false.
  5. 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.
  6. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  7. 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 and y are value

所以首先,给 xy 值。

然后忘记“blah”,1 很重要。 xy 必须是同一类型才能通过第 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/

相关文章:

javascript - 如何使用 PHP Mailer 发送附件而不移动到服务器

javascript - 动态添加时 onKeydown 不起作用

javascript - Mootools 动态获取下拉列表底部

javascript - 如何自定义样式 angular-bootstrap-toggle?

javascript - 从链接提交表单并获取 $_Post 值

javascript - MVC 局部 View 中的 JQuery ui 自动完成功能只能工作一次

javascript - 我无法获取我的 li 的长度?

JavaScript 代码阻塞 CSS

javascript - 如何乘或加动态 javascript 输入字段的值

javascript - 是否可以将数组移出主js文件并将其导入?