Skip to content Skip to sidebar Skip to footer

Array Comparison Failure

Long story short. Why is console.log(obj.hello[0].w == ['hi','hi']); // false in the following: var obj = { 'hello':[ {'w':['hi','hi']} ] } console.log(obj.hello[0].w);

Solution 1:

In addition to @MightyPork's answer, there are workarounds that are very simple.

The easiest way (supported by modern browsers) is to use JSON.stringify().

JSON.stringify(['hi', 'hi')) === JSON.stringify(['hi', 'hi')) // true

If your browser doesn't support JSON nativley you can include the JSON-js library on your page, which has the same syntax.

This isn't a complete solution. For example, functions always return null, except when they are class instances.

functiona(){ this.val = "something"; }
JSON.stringify([a]) // "[null]"JSON.stringify([new a]) // "[{"val":"something"}]"

Solution 2:

You cannot compare arrays like if they were simple variables. You're comparing references to two different arrays, and that will always be false, regardless of their contents.

If you want to do the check, you will have to compare each value individually.

Post a Comment for "Array Comparison Failure"