Javascript 如何检查两个变量是否具有相同的引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13685079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if two vars have the same reference?
提问by clarkk
How can you check if two or more objects/vars have the same reference?
如何检查两个或多个对象/变量是否具有相同的引用?
回答by Denys Séguret
You use ==or ===:
您使用==或===:
var thesame = obj1===obj2;
If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
如果两个操作数都是对象,那么当操作数引用内存中的同一对象时,JavaScript 会比较相等的内部引用。
回答by Quentin
The equality and strict equality operators will both tell you if two variables point to the same object.
相等和严格相等运算符都会告诉您两个变量是否指向同一个对象。
foo == bar
foo === bar
回答by Rajiv
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.
这里 a==b 将是假的,因为尽管它们的内容相同,但两个变量的引用不同。
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.
如果我现在检查 a==b 那么它将是 true ,因为现在两个变量的引用是相同的。
回答by Bobb Dizzles
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;
}
回答by Mohammad Usman
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:
从 开始ES2015,Object.is()引入了一种新方法,可用于比较和评估两个变量/引用的相同性:
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.
注意:该算法在处理有符号零和 NaN 方面与严格相等比较算法不同。

