How to test if two objects are the same with JavaScript?

前端 未结 5 1999
慢半拍i
慢半拍i 2021-02-15 17:35

I need a function:

function isSame(a, b){
} 

In which, if a and b are the same, it returns true.
, I tried return a === b, b

5条回答
  •  隐瞒了意图╮
    2021-02-15 18:16

    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

    Here is a working example:

    http://jsfiddle.net/FhGpd/

    Update:

    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.

提交回复
热议问题