Object.is()与===

有一篇面经中提到面试官提问,如何判断两个变量相等?

在ES6之前,我们使用===来判断两个变量是否相等。ES6中增加了一个方法Object.is(val1,val2)来比较两个变量。那么两者有什么不同之处呢

ECMA规范中的Object.is()执行过程如下:

/* Object.is(x,y)
1、If Type(x) is different from Type(y), return false. //比较类型,不同返回false。typeof x/y
2、If Type(x) is Number, then
  a、If x is NaN and y is NaN, return true.     //NaN与NaN相等
  b、If x is +0 and y is -0, return false.      //+0与-0不相等
  c、If x is -0 and y is +0, return false.      //-0与+0不相等
  d、If x is the same Number value as y, return true.   //数字类型,值不同则不相等
  e、Return false.
3、Return SameValueNonNumber(x, y).
*/

/* sameValueNonNumber(x,y)
1、Assert: Type(x) is not Number.   //x不是数字
2、Assert: Type(x) is the same as Type(y).      //x与y类型相同
3、If Type(x) is Undefined, return true.        //如果typeof x是undefined,则y也是undefined,两者相等
4、If Type(x) is Null, return true.             //typeof x是Null,则y也是Null,则两者相等
5、If Type(x) is String, then                   //字符类型的,值相同则相等
  If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false.
6、If Type(x) is Boolean, then                 //boolean,值相同则相等
  If x and y are both true or both false, return true; otherwise, return false.
7、If Type(x) is Symbol, then                 //symbol类型的,值相同则相等
  If x and y are both the same Symbol value, return true; otherwise, return false.
8、If x and y are the same Object value, return true. Otherwise, return false. //object类型的,同一个对象则相等
*/

  

===运算符的规范如下:

/* 
1、If Type(x) is different from Type(y), return false.
2、If Type(x) is Number, then
  a、If x is NaN, return false.
  b、If y is NaN, return false.
  c、If x is the same Number value as y, return true.
  d、If x is +0 and y is -0, return true.
  e、If x is -0 and y is +0, return true.
  f、Return false.
3、Return SameValueNonNumber(x, y). 
*/

  

===与Object.is()主要差别是NaN、+0、-0这几个特殊的数字类型上。如果是需要判断这几个值,可以选择Object.is(),其他情况下,依然推荐使用===

 

posted @ 2019-11-12 01:30  Jamie0327  阅读(137)  评论(0编辑  收藏  举报
levels of contents