Skip to content

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

Description

@sisterAn

使用 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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions