如何检查两个或多个对象/变量是否具有相同的引用?
问问题
50705 次
5 回答
99
于 2012-12-03T14:15:42.827 回答
18
相等和严格相等运算符都会告诉您两个变量是否指向同一个对象。
foo == bar
foo === bar
于 2012-12-03T14:16:00.023 回答
11
对于像对象这样的引用类型,==或===运算符仅检查其引用。
例如
let a= { text:'my text', val:'my val'}
let b= { text:'my text', val:'my val'}
这里 a==b 将是错误的,因为两个变量的引用不同,尽管它们的内容相同。
但如果我把它改成
a=b
如果我现在检查 a==b 那么它将是 true ,因为这两个变量的引用现在是相同的。
于 2019-02-14T09:56:52.410 回答
7
从开始ES2015
,引入了一种新方法Object.is()
,可用于比较和评估两个变量/引用的相同性:
下面是几个例子:
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
演示:
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));
注意:此算法在处理有符号零和 NaN 方面与严格等式比较算法不同。
于 2020-05-03T18:38:19.597 回答
0
可能的算法:
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;
}
于 2012-12-03T15:04:28.707 回答