Why does !!1==“1” equal true and !!2==“2” equal false?

后端 未结 5 1440
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 15:47

As the title states, why does:

> !!1==\"1\"

equal

True

and

> !!2==\"2\"
         


        
5条回答
  •  一整个雨季
    2020-12-07 16:08

    !!1 is equal to true, and "1" is equal to true ("0" is false, so is every other string). So !!1 == "1" evaluates to true == true, which of course returns true.

    !!2 is also equal to true. As I mentioned earlier, "2" is not "1", so it's false. Therefore, we have true == false, which of course returns false.

    If you want to see if 2 (a number) is equal to "2" (a string representation of a number), then all you have to do is 2 == "2", which evaluates to 2 == 2, which is true. The difference is that we're not comparing a boolean against a boolean. We're comparing a number against a number.

    Basically, putting !! in front of a number converts to a boolean, which forces JavaScript to cast your string to a boolean instead of a number.

提交回复
热议问题