简体   繁体   English

ECMA-262 ===算法说明

[英]ECMA-262 === algorithm explanation

I was trying to understand the exact algorithm for the === operator in JavaScript. 我试图了解JavaScript中===运算符的确切算法。 It is defined as something like 它被定义为类似

The comparison x === y, where x and y are values, produces true or false. 比较x === y(其中x和y是值)会产生true或false。 Such a comparison is performed as follows: 这样的比较执行如下:

  1. If Type(x) is different from Type(y), return false. 如果Type(x)与Type(y)不同,则返回false。
  2. If Type(x) is Undefined, return true. 如果Type(x)为Undefined,则返回true。
  3. If Type(x) is Null, return true. 如果Type(x)为Null,则返回true。
  4. If Type(x) is Number, then 如果Type(x)是Number,则
    • If x is NaN, return false. 如果x为NaN,则返回false。
    • If y is NaN, return false. 如果y为NaN,则返回false。
    • If x is the same Number value as y, return true. 如果x与y相同,则返回true。
    • If x is +0 and y is −0, return true. 如果x为+ 0,y为−0,则返回true。
    • If x is −0 and y is +0, return true. 如果x为-0,y为+0,则返回true。
    • Return false. 返回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); 如果Type(x)为String,则如果x和y是完全相同的字符序列(相同的长度和相同位置的相同字符),则返回true;否则,返回true。 otherwise, return false. 否则,返回false。
  6. If Type(x) is Boolean, return true if x and y are both true or both false; 如果Type(x)为布尔值,则如果x和y均为true或均为false,则返回true;否则,返回false。 otherwise, return false. 否则,返回false。
  7. Return true if x and y refer to the same object. 如果x和y指向同一对象,则返回true。 Otherwise, return false. 否则,返回false。

Now if I write something like 现在,如果我写类似

var t1 = undefined,t2 = 2;
typeof(t1); //"undefined"
typeof(t2); //"number"

t1 === t2; //returns false ?????

Consider point 2 and 3: It should return true instead. 考虑第2点和第3点:它应该返回true。 I am testing it in Chrome 15.0.874.106 m. 我正在Chrome 15.0.874.106 m中进行测试。 Can somebody explain what exactly is going on in this case? 有人可以解释在这种情况下到底发生了什么吗?

You have to go in order, If Type(x) is different from Type(y), return false. 您必须按顺序进行操作, If Type(x) is different from Type(y), return false. . Since false is already returned, it never gets to point 2 or 3. 由于已经返回false,因此它永远不会指向点2或3。

Considering 1: If Type(x) is different from Type(y), return false. 考虑1: If Type(x) is different from Type(y), return false. ,
t1 === t2 should indeed return false. t1 === t2实际上应该返回false。

t1 is undefined , while t2 is a number. t1undefined ,而t2是数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM