qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

第342题(2020-11-04):编程题:如何判断两个变量相等(阿里) #345

Open qappleh opened 3 years ago

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

其中: