JavaScript-Algorithms icon indicating copy to clipboard operation
JavaScript-Algorithms copied to clipboard

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

Open sisterAn opened this issue 4 years ago • 3 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

sisterAn avatar Oct 12 '20 22:10 sisterAn

避免+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;
  }
}

syc666 avatar Oct 13 '20 07:10 syc666

Object.is(value1, value2);

jasonting5 avatar Oct 13 '20 09:10 jasonting5

/**
 * 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))

xllpiupiu avatar Oct 05 '21 11:10 xllpiupiu