为什么两个具有相同值的对象不相等? [英] Why are two objects with the same values not equal?

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

问题描述

我在控制台中运行以下命令,为什么输出为false.不问如何比较两个对象,而是为什么这两个对象不相同.

 >a = {相同:相同"}对象{same:"same"}>b = {相同:相同"}对象{same:"same"}>a === b错误的>a == b错误的 

解决方案

即使两个对象具有相同的内容,它们也永远不会相同,因为 Object 的两个不同实例永远都不相等.

比较两个对象时,JavaScript会比较内部引用,内部引用仅在两个操作数都引用内存中的同一对象,不检查键和值时才相等,因此对象的内容无关紧要,操作数都必须引用同一对象以在比较中返回true.

I run the following in console why is the output false. Not asking how to compare two objects but why these two objects are not same.

> a = {same:'same'}
Object {same: "same"}
> b = {same:'same'}
Object {same: "same"}
> a === b
false
> a == b
false

解决方案

Two objects are never the same even if they have the same content, as two different instances of Object is never equal.

When comparing two object, JavaScript compares internal references which are equal only when both operands refer to the same object in memory, keys and values are not checked, so the content of the object doesn't matter, the operands both have to reference the same object to return true in a comparison.

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

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