为什么两个空的JavaScript函数或普通对象不相等 [英] Why are 2 empty JavaScript functions or plain objects not equal

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

问题描述

在此代码段中,我定义了两个函数,将它们及其字符串表示形式输出到控制台,并进行比较:

In this snippet of code I'm defining two functions, outputting them and their string representations to console, and also comparing them:

var a = function func() {},
    b = function func() {};

// string representations are equal
console.log(a.toString());
console.log(b.toString());
console.log(a.toString() == b.toString());
console.log(a.toString() === b.toString());

// functions seem to be equal
console.log(a);
console.log(b);

// but they're not really as this prints false
console.log(a == b);
console.log(a === b);

为什么它们不相等?

对于空的普通对象,即 {} ,当然也会发生同样的情况.

Same happens of course to empty plain objects, i.e. {}.

有趣的是,在这种情况下lodash的 isEqual 返回 true : _.isEqual({},{}); false ,其中: _.isEqual(function(){},function(){}).但这当然不是任何证明,而只是实现平等的方式.

Funny thing though is that lodash isEqual returns true in this case: _.isEqual({}, {}); and false in this: _.isEqual(function () {}, function () {}). But of course it's not any proof, it's just the way of implementation of equality.

推荐答案

功能不是对象,因此一切都归结为2个对象的比较,然后根据

Functions are nothing else than objects, so it all comes back to the comparison of 2 objects, and then according to MDN:

等于运算符将转换为非运算符相同类型,然后应用严格比较.如果两个操作数都为对象,然后JavaScript比较相等的内部引用当操作数指向内存中的同一对象时.

The equality operator converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

ECMAScript®中也描述了完全相等比较算法语言规范,而1.f很明显:

如果x和y指向同一个对象,则返回true.否则,返回错误.

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

因此,根据设计,对象总是使用引用进行比较,引用是指向内存中地址的一种指针.如果指向相同,则返回 true ,否则返回 false .

So by design objects are always compared using reference, which is kind of a pointer to the address in memory. If it points to the same, it will return true, if not false is produced.

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

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