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

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

问题描述

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

  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;
};
}

问题很简单:第二个if是什么时候可以实现? / p>

感谢您的关注。

解决方案

同一篇文章


根据===
运算符,这也不一样。 ===运算符(和==运算符)将
数字值-0和+0视为相等,而 则将Number.NaN视为不等于
NaN


逻辑是 NaN!== NaN 是唯一的情况,其中!== 操作符在同一个变量上返回 true ,所以它必须是大约 NaN 比较。然后对 v2 进行相同的检查,并根据结果返回true:如果 v2 比较是 true ,它是关于NaN与NaN相比,所以返回 true ,如果不是则返回 false 因为NaN从不与NaN 不相同。


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 ?

Thank you for your attention.

解决方案

It kinda is written in the same article:

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.

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天全站免登陆