JavaScript equality transitivity is weird

后端 未结 3 697
长情又很酷
长情又很酷 2020-12-01 04:08

I\'ve been reading Douglas Crockford\'s JavaScript: The Good Parts, and I came across this weird example that doesn\'t make sense to me:

\'\' == \'0\'                


        
3条回答
  •  既然无缘
    2020-12-01 05:01

    The answer to this question has to do with how JavaScript handles coercion. In the case of ==, strings are coerced to be numbers. Therefore:

    '' == '0' is equivalent to '' === '0' (both are strings, so no coercion is necessary).

    0 == '' is equivalent to 0 === 0 because the string '' becomes the number 0 (math.abs('') === 0).

    0 == '0' is equivalent to 0 === 0 for the same reason.

    false == undefined is equivalent to 0 === undefined because JavaScript coerces booleans to be numbers when types don't match

    false == null is equivalent to 0 === null for the same reason.

    null == undefined is true because the spec says so.

    Thanks for asking this question. My understanding of == is much better for having researched it.

提交回复
热议问题