How to check if two vars have the same reference?

后端 未结 5 1331
借酒劲吻你
借酒劲吻你 2020-12-13 03:23

How can you check if two or more objects/vars have the same reference?

相关标签:
5条回答
  • 2020-12-13 03:48

    For reference type like objects, == or === operators check its reference only.

    e.g

    let a= { text:'my text', val:'my val'}
    let b= { text:'my text', val:'my val'}
    

    here a==b will be false as reference of both variables are different though their content are same.

    but if I change it to

    a=b
    

    and if i check now a==b then it will be true , since reference of both variable are same now.

    0 讨论(0)
  • 2020-12-13 03:51

    You use == or === :

    var thesame = obj1===obj2;
    

    From the MDN :

    If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

    0 讨论(0)
  • 2020-12-13 03:52

    Possible algorithm:

    Object.prototype.equals = function(x)
    {
      var p;
      for(p in this) {
          if(typeof(x[p])=='undefined') {return false;}
      }
    
      for(p in this) {
          if (this[p]) {
              switch(typeof(this[p])) {
                  case 'object':
                      if (!this[p].equals(x[p])) { return false; } break;
                  case 'function':
                      if (typeof(x[p])=='undefined' ||
                          (p != 'equals' && this[p].toString() != x[p].toString()))
                          return false;
                      break;
                  default:
                      if (this[p] != x[p]) { return false; }
              }
          } else {
              if (x[p])
                  return false;
          }
      }
    
      for(p in x) {
          if(typeof(this[p])=='undefined') {return false;}
      }
    
      return true;
    }
    
    0 讨论(0)
  • The equality and strict equality operators will both tell you if two variables point to the same object.

    foo == bar
    foo === bar
    
    0 讨论(0)
  • 2020-12-13 04:03

    As from ES2015, a new method Object.is() has been introduced that can be used to compare and evaluate the sameness of two variables / references:

    Below are a few examples:

    Object.is('abc', 'abc');     // true
    Object.is(window, window);   // true
    Object.is({}, {});           // false
    
    const foo = { p: 1 };
    const bar = { p: 1 };
    const baz = foo;
    
    Object.is(foo, bar);         // false
    Object.is(foo, baz);         // true
    

    Demo:

    console.log(Object.is('abc', 'abc'));
    console.log(Object.is(window, window));
    console.log(Object.is({}, {}));
    
    const foo = { p: 1 };
    const bar = { p: 1 };
    const baz = foo;
    
    console.log(Object.is(foo, bar));
    console.log(Object.is(foo, baz));

    Note: This algorithm differs from the Strict Equality Comparison Algorithm in its treatment of signed zeroes and NaNs.

    0 讨论(0)
提交回复
热议问题