Js equal in

Outline

Today learning jest, found the time to look at the document jest uses Object.is (), have not seen before, so recorded for later reference when developing, we believe it is useful to others.

Note: Object.is documents in here

Object.is

If any of the following are the same, Object.is (value1, value2) returns true:

  • Both values ​​are undefined
  • Both values ​​are null
  • Both values ​​are true or both false
  • Two values ​​is a string of characters consisting of the same number in the same order
  • Both values ​​point to the same object
  • And two digital values ​​are
  • We are positive zero +0
  • Are negative zero -0
  • Is NaN
  • Other numbers are the same except for the zero, and NaN

equal

  1. == do implicit conversion, the number of types of operations on both sides into the same.
  2. === not do an implicit conversion, but will be considered equal -0 +0, and that Number.NaN not equal to NaN.
  3. Object.is () does not do an implicit conversion, but think -0 +0 are not equal, and Number.NaN equal NaN.

Examples are as follows:

Object.is('foo', 'foo');     // true
Object.is(window, window);   // true

Object.is('foo', 'bar');     // false
Object.is([], []);           // false

var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo);         // true
Object.is(foo, bar);         // false

Object.is(null, null);       // true

// 特例
Object.is(0, -0);            // false
Object.is(0, +0);            // true
Object.is(-0, -0);           // true
Object.is(NaN, 0/0);         // true

Object.is of 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;
    }
  };
}

Guess you like

Origin www.cnblogs.com/yangzhou33/p/11403143.html