简体   繁体   中英

Javascript string equality

each element contains the same value. When checked against this value by themselves, everything checks out. But when compared against eachother, they are not shown as being equal. help! thanks!

time[x] == "2013-02-26 14:00:00"   ?

true

reference[x] == "2013-02-26 14:00:00"  ?

true

time[x] == reference[x]  ?

false

time[x].valueOf() == reference[x].valueOf()  ?

false

This might happen because the two variables are of different types.

In case one of the variables holds a Date instance and the other a String , comparing both of them to a string literal will return true, while comparing their valueOf() results will return false, since valueOf() of a Date returns number of milliseconds since epoch, not the human-readable representation of a date (as opposed to toString() ).

var a = new Date()
a.toString() //"Wed Feb 27 2013 01:41:51 GMT+0300 (MSK)"
a.valueOf()  //1361918511306

var b = "Wed Feb 27 2013 01:41:51 GMT+0300 (MSK)"
b.toString() //"Wed Feb 27 2013 01:41:51 GMT+0300 (MSK)"
b.valueOf()  //"Wed Feb 27 2013 01:41:51 GMT+0300 (MSK)"

a == "Wed Feb 27 2013 01:41:51 GMT+0300 (MSK)" //true
b == "Wed Feb 27 2013 01:41:51 GMT+0300 (MSK)" //true
a == b //true
a === b //false - types are being compared as well
a.valueOf() == b.valueOf() //false - 1361918511306 compared to "Wed Feb 27 2013 01:41:51 GMT+0300 (MSK)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM