sisterAn / JavaScript-Algorithms

基础理论+JS框架应用+实践,从0到1构建整个前端算法体系
5.49k stars 633 forks source link

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

Open sisterAn opened 4 years ago

sisterAn commented 4 years ago

使用 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提供三种不同的值比较操作:

其中:

syc666 commented 4 years ago

避免+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;
  }
}
jasonting5 commented 4 years ago
Object.is(value1, value2);
xllpiupiu commented 3 years ago
/**
 * 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))