如何测试两个对象是否与JavaScript相同? [英] How to test if two objects are the same with JavaScript?

查看:61
本文介绍了如何测试两个对象是否与JavaScript相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个功能:

function isSame(a, b){
} 

其中,如果a和b相同,则返回true。

,我试过返回=== b ,但我发现 [] === [] 将返回false。

我希望这个函数可以给出一些结果:

In which, if a and b are the same, it returns true.
, I tried return a === b, but I found that [] === [] will return false.
Some results that I expect this function can gave:

isSame(3.14, 3.14);  // true  
isSame("hello", "hello"); // true  
isSame([], []); // true  
isSame([1, 2], [1, 2]); // true  
isSame({ a : 1, b : 2}, {a : 1, b : 2}); //true  
isSame([1, {a:1}], [1, {a:1}]);  //true


推荐答案

有一些例子,改编自方案,在Crockford的网站上。具体来说,请查看:

There are some examples, adapted from scheme, on Crockford's site. Specifically, check out:

function isEqual(s1, s2) {
    return isAtom(s1) && isAtom(s2) ? isEqan(s1, s2) :
            isAtom(s1) || isAtom(s2) ? false :
            isEqlist(s1, s2);
}

这一切都可以在这里找到:

It can all be found here:

http://javascript.crockford.com/little.js

这是一个有效的例子:

http://jsfiddle.net/FhGpd/

刚刚根据OP编写了一些测试用例。结果我需要修改sub1函数来检查< = 0 not === 0否则isEqual(3.14,3.14)炸毁堆栈。此外,isEqual不适用于对象比较,因此您可以自己使用。但是,如果您按照Crockford网站上的示例进行操作,您将看到编写可用于检查对象相等性的递归方法是多么容易和有趣。

Just wrote some test cases based on the OP. Turns out I needed to modify the sub1 function to check <= 0 not === 0 otherwise isEqual(3.14, 3.14) blew the stack. Also, isEqual does not work for object comparison, so you are on your own there. However, if you follow the examples on Crockford's site you will see how easy and fun it is to write recursive methods that could be used to check for object equality.

这篇关于如何测试两个对象是否与JavaScript相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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