In Javascript, == “” evaluates to true. Why is it so?

后端 未结 8 1585
野性不改
野性不改 2020-12-13 22:18

If I do 0 == \"0\" it evaluates to true. Try,

if( -777 == \"-777\" ) alert(\"same\");

alert happens.

And, it\'s also noticeable th

8条回答
  •  轮回少年
    2020-12-13 22:34

    Because Javascript is loosely typed, it will silently cast your variables depending on the operation and the type of the other variables in the operation.

    alert ("5" - 1);  // 4  (int)
    alert ("5" + 1);  // "51" (string) "+" is a string operator, too
    alert ("5" == 5); // true
    

    What you might want to look at is identity checking (===). That makes sure the variables are identical, not merely equal.

    alert("5" == 5);  // true, these are equal
    alert("5" === 5); // false, these are not identical.
    

    Also see this question: How do the equality and identity comparison operators differ? PHP's implementation is very similar to javascript's.

提交回复
热议问题