sisterAn / JavaScript-Algorithms

基础理论+JS框架应用+实践,从0到1构建整个前端算法体系

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

阿里:如何判断两个变量相等

sisterAn opened this issue · comments

使用 API: Object.is() 方法判断两个值是否为同一个值

Object.is(x, y)

Polyfill:

if (!Object.is) {
  Object.is = function(x, y) {
    // SameValue algorithm
    if (x === y) { // Steps 1-5, 7-10
      // Steps 6.b-6.e: +0 != -0
      return x !== 0 || 1 / x === 1 / y;
    } else {
      // Step 6.a: NaN == NaN
      return x !== x && y !== y;
    }
  };
}

扩展:

JavaScript提供三种不同的值比较操作:

  • 严格相等比较:使用 ===
  • 抽象相等比较:使用 ==
  • 以及 Object.is (ECMAScript 2015/ ES6 新特性):同值相等

其中:

  • ===:进行相同的比较,不进行类型转换 (如果类型不同, 只是总会返回 false )
  • ==:执行类型转换,比较两个值是否相等
  • Object.is :与 === 相同,但是对于 NaN-0+0 进行特殊处理, Object.is(NaN, NaN) 为 trueObject.is(+0, -0)false
commented

避免+0,-0,1/-Infinity,1/Infinity都相等。

function is(x, y) {
  if (x === y) {
    return x !== 0 || y !== 0 || 1 / x === 1 / y;
  } else {
    return x !== x && y !== y;
  }
}
Object.is(value1, value2);
/**
 * https://www.cnblogs.com/lindasu/p/7471519.html
 * === Object.is
 * https://github.com/sisterAn/JavaScript-Algorithms/issues/116
 */
Object._is = function(x,y) {
    if(x===y) {
        return x!==0||1/x===1/y
    } else {
        return x!==x&&y!==y
    }
}
console.log(Object._is(NaN,NaN))