Javascript 为什么两个相同的对象彼此不相等?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11704971/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:47:56  来源:igfitidea点击:

Why are two identical objects not equal to each other?

javascript

提问by Maxx

Seems like the following code should return a true, but it returns false.

似乎下面的代码应该返回一个 true,但它返回 false。

var a = {};
var b = {};

console.log(a==b); //returns false
console.log(a===b); //returns false

How does this make sense?

这有什么意义?

回答by josh3736

The only difference between regular (==) and strict (===) equality is that the strict equality operator disables type conversion. Since you're already comparing two variables of the same type, the kind of equality operator you use doesn't matter.

常规 ( ==) 和严格 ( ===) 相等之间的唯一区别是严格相等运算符禁用类型转换。由于您已经在比较相同类型的两个变量,因此您使用的相等运算符的类型并不重要。

Regardless of whether you use regular or strict equality, object comparisons only evaluate to trueif you compare the same exact object.

无论您使用常规相等还是严格相等,对象比较仅true在您比较相同的完全对象时评估为。

That is, given var a = {}, b = a, c = {};, a == a, a == b, but a != c.

也就是说,给定var a = {}, b = a, c = {};, a == a, a == b, , 但是a != c

Two different objects (even if they both have zero or the same exact properties) will never compare equally. If you need to compare the equality of two object's properties, this question has very helpful answers.

两个不同的对象(即使它们都具有零或完全相同的属性)永远不会进行相等的比较。如果您需要比较两个对象属性的相等性,这个问题有非常有用的答案

回答by T.J. Crowder

How does this make sense?

这有什么意义?

Because "equality" of object references, in terms of the ==and ===operators, is purelybased on whether the references refer to the sameobject. This is clearly laid out in the abstract equality comparison algorithm(used by ==) and the strict equality comparison algorithm(used by ===).

因为对象引用的“相等性”,就==and===运算符而言,纯粹是基于引用是否指向同一个对象。这在抽象相等比较算法(由 使用==)和严格相等比较算法(由 使用===)中有明确规定。

In your code, when you say a==bor a===b, you're not comparing the objects, you're comparing the references in aand bto see if they refer to the same object. This is just how JavaScript is defined, and in line with how equality operators in many (but not all) other languages are defined (Java, C# [unless the operator is overridden, as it is for string], and C++ for instance).

在您的代码中,当您说a==bor 时a===b,您不是在比较objects,而是在比较 中的引用ab查看它们是否引用同一个对象。这是JavaScript的只是如何定义的,并且在许多(但不是全部)其他语言有多么平等运营线的定义(Java,C#[除非操作员被覆盖,因为它是string],和C ++为例)。

JavaScript has no inbuilt concept of equivalence, a comparison between objects that indicates whether they're equivalent (e.g., have the same properties with the same values, like Java's Object#equals). You can define one within your own codebase, but there's nothing intrinsic that defines it.

JavaScript 没有内置的等价概念,对象之间的比较表明它们是否等价(例如,具有相同的属性和相同的值,如 Java 的Object#equals)。您可以在自己的代码库中定义一个,但没有任何内在定义它。

回答by Charlie Lynch

As from The Definitive Guide to Javascript.

来自 The Definitive Guide to Javascript。

Objects are not compared by value: two objects are not equal even if they have the same properties and values. This is true of arrays too: even if they have the same values in the same order.

对象不按值进行比较:即使两个对象具有相同的属性和值,它们也不相等。数组也是如此:即使它们具有相同顺序的相同值。

var o = {x:1}, p = {x:1};  // Two objects with the same properties
o === p                    // => false: distinct objects are never equal 
var a = [], b = [];        // Two distinct, empty arrays 
a === b                    // => false: distinct arrays are never equal 

Objects are sometimes called reference types to distinguish them from JavaScript's primitive types. Using this terminology, object values are references, and we say that objects are compared by reference: two object values are the same if and only if they refer to the same underlying object.

对象有时被称为引用类型,以区别于 JavaScript 的原始类型。使用这个术语,对象值是引用,我们说对象是按引用比较的:两个对象值相同当且仅当它们引用相同的底层对象。

var a = {};   // The variable a refers to an empty object. 
var b = a;    // Now b refers to the same object. 
b.property = 1;     // Mutate the object referred to by variable b. 
a.property          // => 1: the change is also visible through variable a. 
a === b       // => true: a and b refer to the same object, so they are equal. 

If we want to compare two distinct objects we must compare their properties.

如果我们想比较两个不同的对象,我们必须比较它们的属性。

回答by Karoly Horvath

===, the strictly equaloperator for objects checks for identity.

===,对象的严格相等运算符检查身份。

Two objects are strictly equal if they refer to the same Object.

如果两个对象引用同一个对象,则它们严格相等。

Those are two different objects, so they differ.

这是两个不同的对象,所以它们是不同的。

Think of two empty pages of paper. Their attributes are the same, yet they are not the same thing. If you write something on one of them, the other wouldn't change.

想想两张空白的纸页。他们的属性是一样的,但又不是一回事。如果你在其中一个上写一些东西,另一个就不会改变。

回答by Christina

use JSON.stringify(objname);

var a = {name : "name1"};
var b = {name : "name1"};

var c = JSON.stringify(a);
var d = JSON.stringify(b);

c==d;
//true

回答by Matt Way

How does this make sense?

这有什么意义?

Imagine these two objects:

想象一下这两个对象:

var a = { someVar: 5 }
var b = { another: 'hi' }

Now if you did a === b, you would intuitively think it should be false (which is correct). But do you think it is false because the objects contain different keys, or because they are different objects? Next imagine removing the keys from each object:

现在,如果你这样做了a === b,你会直觉地认为它应该是假的(这是正确的)。但是你认为这是因为对象包含不同的键,还是因为它们是不同的对象?接下来想象从每个对象中删除键:

delete a.someVar
delete b.another

Both are now empty objects, but the equality check will still be exactly the same, because you are still comparing whether or not aand bare the same object (not whether they contain the same keys and values).

两者现在都是空对象,但相等性检查仍将完全相同,因为您仍在比较ab是否是同一个对象(而不是它们是否包含相同的键和值)。

回答by Anze Jarni

This is a workaround: Object.toJSON(obj1) == Object.toJSON(obj2)

这是一种解决方法: Object.toJSON(obj1) == Object.toJSON(obj2)

By converting to string, comprasion will basically be in strings

通过转换为字符串,比较基本上将在字符串中