开发者

Is all JavaScript literal object different from each other

开发者 https://www.devze.com 2023-04-10 03:04 出处:网络
I have this: var g = [{a:\'a\'},{a:\'2\'},{a:\'3\'}] var c = [{a:\'4\'},{a:\'2\'},{a:\'5\'}] The following statement:

I have this:

var g = [{a:'a'},{a:'2'},{a:'3'}]
var c = [{a:'4'},{a:'2'},{a:'5'}]

The following statement:

g[1] == c[1]

Returns false, e开发者_如何学编程ven though the objects look the same. Is there any way I can compare them literally so it will return me true instead of false?


You could encode them as JSON:

JSON.stringify(g[1]) == JSON.stringify(c[1])

You might also be interested in the answers to this related question on identifying duplicate Javascript objects.

For a more complex option, you might look at the annotated source code for Underscore's _.isEqual() function (or just use the library).


The == operator checks for reference equality. The only way to do what you want would be a memberwise equality test on the objects.

This ought to work:

function memberwiseEqual(a, b) {
    if(a instanceof Object && b instanceof Object) {
        for(key in a)
            if(memberwiseEqual(a[key], b[key]))
                return true;
        return false;
    }
    else
        return a == b;
}

Be wary of cases like these:

var a = {};
a.inner = a; //recursive structure!


here you compare the reference in the memory ,not its value try this and you will get true :

g[1]['a'] === c[1]['a']


In JavaScript variables which are objects (including arrays) are actually references to the collection. So when you write var x = { a: 2 } and var y = { a: 2 } then x and y become references to two different objects. So x will not equal y. But, if you did y = x then they would (because they would share the same reference). But then if you altered either object the other would be altered too.

So, when dealing with objects and arrays, by saying == you are checking if the two references are the same. In this case they are not.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号