zoukankan      html  css  js  c++  java
  • 为什么你应该使用 Object.is() 进行相等性比较(译)

    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个操作数中的一个强制转换为另一种类型然后进行比较”而产生意外结果。

    1 0 == ' ' //true
    2 null == undefined //true
    3 [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提供了三等运算符,三等运算符更加严格并且不会将操作数进行强制类型转换。然而三等运算符也不是最好的解决方案,也存在问题:

    1 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()”,它更好,更精确,它具有与“ ===”相同的功能,而且在某些特殊情况下,其表现还不错:

    1 Object.is(0 , ' '); //false
    2 Object.is(null, undefined); //false
    3 Object.is([1], true); //false
    4 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

  • 相关阅读:
    《计算机图形学-基于3D图形开发技术》读书笔记
    【转】OpenGL和D3D 矩阵对比
    【转】D3D中详细拾取操作
    根据点坐标改变字体显示位置
    静态常量和常量在类中的初始化
    MFC单文档中使用D3D9
    单文档切换OpenGL视图
    超大地形的处理 (Terrain Visualization)【转自知乎】
    又出现这种问题。。。
    属性
  • 原文地址:https://www.cnblogs.com/code-bug/p/12212957.html
Copyright © 2011-2022 走看看