Title: Why you should use Object.is() in equality comparison

Author: TarekAlQaddy

Website: https://www.jstips.co/en/javascript/why-you-should-use-Object.is()-in-equality-comparison/


We all know that JavaScript is loosely typed and in some cases it fall behind specially when it comes to equality comparison with ‘==’, comparing with ‘==’ gives unexpected results due to whats called coercion or casting “converting one of the 2 operands to the other’s type then compare”.

我们都知道JavaScript是弱类型语言,在某些情况下,当与“ ==”进行相等性比较时,它特别落后。使用“ ==”进行比较可能会“将2个操作数中的一个强制转换为另一种类型然后进行比较”而产生意外结果。

 0 == ' ' //true
null == undefined //true
[1] == true //true

So they provided us with the triple equal operator ‘===’ which is more strict and does not coerce operands, However comparing with ‘===’ is not the best solution you can get:

因此Javascript提供了三等运算符,三等运算符更加严格并且不会将操作数进行强制类型转换。然而三等运算符也不是最好的解决方案,也存在问题:

 NaN === NaN //false

The great news that in ES6 there is the new ‘Object.is()’ which is better and more precise it has the same features as ‘===’ and moreover it behaves well in some special cases:

好消息是,在ES6中有一个新的“ Object.is()”,它更好,更精确,它具有与“ ===”相同的功能,而且在某些特殊情况下,其表现还不错:

 Object.is(0 , ' '); //false
Object.is(null, undefined); //false
Object.is([1], true); //false
Object.is(NaN, NaN); //true

Mozilla team doesn’t think that Object.is is “stricter” than ‘===’ they say that we should think of how this method deal with NaN, -0 and +0 but overall I think it is now a good practice in real applications.

Mozilla团队不认为"Object.is()"比“ ===”更“严格”,应该考虑该方法如何处理NaN,-0和+0,但总的来说,我认为这是一种最佳实践。

Now this table illustrates..

下表所示:

参考:

Object.is() - JavaScript | MDN

Equality comparisons and sameness

最新文章

  1. <mvc:annotation-driven/>与<context:annotation-config/>的区别
  2. The type String cannot be constructed. You must configure the container to supply this value.
  3. break,continue的使用
  4. Ubuntu 15.10 x64 安装 Android SDK
  5. 【腾讯bugly干货分享】解耦---Hybrid H5跨平台性思考
  6. c#中的委托和事件(转)
  7. IOS自动布局
  8. 用Redis bitmap统计活跃用户、留存
  9. 130道ASP.NET面试题
  10. Eclipse中设置tomcat的启动内存
  11. getResource(String name)用法及源码分析
  12. python爆破定长密码脚本
  13. 【学习笔记】深入理解超时调用(setTimeout)和间歇调用(setInterval)
  14. 实现select联动效果,数据从后台获取
  15. BugKu 这是一张单纯的图片
  16. Java集合List、Set、Map
  17. 记一次laravel远程关联查询
  18. java得到日期相减的天数
  19. Hibernate的实体类中为什么要继承Serializable?
  20. oracle forall

热门文章

  1. HDU_5058_set
  2. 题解 CF1294F 【Three Paths on a Tree】
  3. MySQL关系型数据库基础操作
  4. nginx-tengine集合
  5. 当前行的td值传入模态框
  6. vue简单实现
  7. cornerstone使用beyond compare比较工具
  8. Serverless + Egg.js 后台管理系统实战
  9. MySQL命令随手记之alter
  10. 解决egg-mysql连接数据库报错问题