Javascript:为什么两个对象不相等? [英] Javascript: Why are two objects not equal?

查看:1049
本文介绍了Javascript:为什么两个对象不相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在SO上有类似的问题,但是没有一个能提供我想要的答案。

I know there are similar questions to this on SO, but none of them provide the answer I am looking for.

在JavaScript中,如果你这样做,结果将是错误的:

In JavaScript, if you do the following, the result will be false:

< img src =https://i.stack.imgur.com/c5T8t.pngalt =在此输入图像说明>

我知道它与规范中如何定义JavaScript有关,但为什么会这样呢?这是违反直觉的。

I know it is to do with how JavaScript is defined in the spec, but why is it like that? It is counter-intuitive.

如果(string===string)导致 true ,那么为什么({} === {})导致为真?

If ("string" === "string") results in being true, then why doesn't ({ } === { }) result in being true?

我看到某个地方的等式算法被设计成类似于C ++或C#,但这就像发明了一个全新的引擎,使用了十分之一的燃料并且没有使用它纯粹是为了与其他汽车保持一致。

I saw somewhere that the equality algorithm was designed to be similar to that of C++ or C#, but that's like inventing a brand new engine that uses 1/10th of the fuel and not using it purely for consistency with other cars.

为什么JavaScript以这种方式定义?这个决定背后有原因吗?或者它是否只是这样看到做完成的事情?

Why was JavaScript defined in this way? Is there a reason behind this decision? Or was it just so it was seen doing the done thing?

推荐答案

{} 是在javascript中创建对象的文字。那就是你可以替换

{} is a literal to create object in javascript. That is you can replace

var obj = new Object();

with

var obj = {};

所以每次使用 {} 你正在创建一个新对象。

So any time you use {} you are creating a new object.

您提到的行 {} == {} 会创建两个不同的对象,两者都没有属性。相同它们是相同的,就像你有 equals(obj1,obj2)方法一样,它比较obj1和obj2的属性,如果两个属性的值都相同,则返回true 。

The line you mentioned, {} == {} creates two different objects and both has no properties. Identically they are same, like if you have equals(obj1, obj2) method which compares properties of both obj1 and obj2 and it should return true if both has same value for all properties.

但是 == 运营商不会检查属性。它检查两个对象是否都指向同一个对象/参考。

But == operator will not check for properties. It checks if both the objects are pointing to same object/reference.

然后

var obj1 = {};
obj2 = obj1;
console.log(obj2 == obj1); //returns true

返回true,因为obj1和obj2指向相同的引用。

returns true because obj1 and obj2 are pointing to same reference.

最后,关于字符串abc==abc,这里 == operator查找实际的字符串内容并根据它返回true / false。

Finally, regarding string "abc" == "abc", here == operator looks for actual string contents and returns true/false based on it.

这篇关于Javascript:为什么两个对象不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆