0

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);                // ['hi','hi']
console.log(obj.hello[0].w == ['hi','hi']); // false ??? Why is it false?
console.log(obj.hello[0].w[0] == 'hi');     // true
console.log(obj.hello[0].w[0] == ['hi']);   // true
console.log(obj.hello[0].w[0] === ['hi']);  // false
console.log(obj.hello[0].w[0] === 'hi');    // true

If obj.hello[0].w != ['hi','hi'], then what is the 'real' value of obj.hello[0].w?

EDIT: I first thought the problem was about JSON but it turned out it's about comparing objects. Sorry, for duplicate.

icedwater
  • 4,701
  • 3
  • 35
  • 50
RainingChain
  • 7,397
  • 10
  • 36
  • 68

2 Answers2

2

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.

function a(){ this.val = "something"; }
JSON.stringify([a]) // "[null]"
JSON.stringify([new a]) // "[{"val":"something"}]"
Brigand
  • 84,529
  • 20
  • 165
  • 173
1

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.

MightyPork
  • 18,270
  • 10
  • 79
  • 133