对象和原始类型相等 [英] Object and primitive type equality

查看:88
本文介绍了对象和原始类型相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道相同的对象不相等,即:

var obj = { name: "Value" };
var obj2 = { name: "Value" };

console.log("obj equals obj2: " + (obj === obj2)); //evaluates to false

然而原始类型是:

var str = "string1";
var str2 = "string1";

console.log("str equals str2: " + (str === str2)); //evaluates to true

我的问题是为什么。为什么对象和原语被区别对待?如果一个对象只是一个空容器,只有你指定放入容器的属性,为什么容器的相同属性不能评估相同?我在SO和其他地方四处寻找这个答案,但没有找到答案。

My question is why. Why are objects and primitives treated differently? If an object is nothing but an empty container, with only the attributes you specify to put in the container, why wouldn't the container's identical attributes evaluate to be the same? I looked around for this answer on SO and elsewhere, but didn't find an answer.

在DOM中,JS对象被视为与原始类型不同的东西吗?

Is a JS object treated as something different in the DOM than a primitive type?

谢谢

推荐答案

这似乎真的是一个关于<的问题code> === 让我们来看看 严格平等比较算法 ,其中第7点说

This seems to really be a question about === so let's look at the Strict Equality Comparison Algorithm, in which point 7 says


返回 true 如果x和y引用同一个对象。否则,返回 false

Return true if x and y refer to the same object. Otherwise, return false.

那么是什么意思同一个对象?这意味着它们不仅看起来像彼此,而且在记忆中也处于相同的位置。这意味着对象 对象 对象的唯一时间是它们是相同的事情。

So what does it mean to be "the same object"? It means they don't just look like eachother, but are at the same place in memory too. This means that the only time when an Object is === to an Object is when they're the same thing.

var a = {},
    b = {}, // identical to `a`
    c = a;  // same as `a`
a === b; // false
a === c; // true
b === c; // false

这篇关于对象和原始类型相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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