如何检查两个变量是否有相同的引用?

如何检查两个或多个对象/变量是否具有相同的引用?

58057 次浏览

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.

The equality and strict equality operators will both tell you if two variables point to the same object.

foo == bar
foo === bar

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;
}

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.

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.