MDN“Object.is"替代方案 [英] MDN "Object.is" alternative proposal

查看:13
本文介绍了MDN“Object.is"替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读 MDN 页面上的Object.is"方法.它为不提供此方法的浏览器提供了替代代码:

I have read the MDN page on the "Object.is" method. It gives an alternative code for the browsers that do not provide this method:

if (!Object.is) {
    Object.is = function(v1, v2) {
        if (v1 === 0 && v2 === 0) {
            return 1 / v1 === 1 / v2;
        }
        if (v1 !== v1) {
            return v2 !== v2;
        }
        return v1 === v2;
    };
}

问题很简单:第二个如果"什么时候才能成立?

The question is simple: when can the second "if" be true ?

感谢您的关注.

推荐答案

它有点写在 同一篇文章:

这也不等同于===操作员.=== 运算符(以及 == 运算符)处理数字值 -0 和 +0 相等,并且 它将 Number.NaN 视为不相等等于 NaN.

This is also not the same as being equal according to the === operator. The === operator (and the == operator as well) treats the number values -0 and +0 as equal, and it treats Number.NaN as not equal to NaN.

逻辑是 NaN !== NaN!== 运算符在同一变量上返回 true 的唯一情况,所以它必须是关于 NaN 的比较.然后它对 v2 进行同样的检查,并根据结果返回 true 或 false:if v2 比较是 true,它是关于NaN 与 NaN 相比,返回 true,如果不是,则返回 false,因为 NaN 永远不会与非 NaN 相同.

The logic is that NaN !== NaN is the only case in which the !== operator returns true on the same variable, so it must be about NaN comparison. It then does the same check on v2 and returns true of false based on the outcome: if v2 comparison is true, it's about NaN compared to NaN so return true, if not then return false because NaN is never the same as something that isn't NaN.

这篇关于MDN“Object.is"替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆