Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sisterAn opened this issue Oct 12, 2020 · 3 comments
Open

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

sisterAn opened this issue Oct 12, 2020 · 3 comments

Comments

@sisterAn
Copy link
Owner

sisterAn commented Oct 12, 2020

使用 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
@syc666
Copy link

syc666 commented Oct 13, 2020

避免+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
Copy link

Object.is(value1, value2);

@xllpiupiu
Copy link

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

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

No branches or pull requests

4 participants