本文介绍了如何确定两个JavaScript对象的相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

严格相等运算符会告诉您两个对象类型是否相等。但是,有没有办法判断两个对象是否相等,非常类似于Java中的哈希码值?

A strict equality operator will tell you if two object types are equal. However, is there a way to tell if two objects are equal, much like the hash code value in Java?

Stack Overflow question 与此问题类似,但需要更多学术答案。上面的场景说明了为什么需要有一个,我想知道是否有任何等效解决方案

Stack Overflow question Is there any kind of hashCode function in JavaScript? is similar to this question, but requires a more academic answer. The scenario above demonstrates why it would be necessary to have one, and I'm wondering if there is any equivalent solution.

推荐答案

为什么重新发明轮子?尝试。它有许多必备功能,例如。

Why reinvent the wheel? Give Lodash a try. It has a number of must-have functions such as isEqual().

_.isEqual(object, other);

它将强制检查每个键值 - 就像本页上的其他示例一样 - 使用和原生优化(如果它们在浏览器中可用)。

It will brute force check each key value - just like the other examples on this page - using ECMAScript 5 and native optimizations if they're available in the browser.

注意:以前这个答案建议,但在修复错误和解决问题方面做得更好。

Note: Previously this answer recommended Underscore.js, but lodash has done a better job of getting bugs fixed and addressing issues with consistency.

这篇关于如何确定两个JavaScript对象的相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 17:14