开发者

Javascript 0 Vs Blank

开发者 https://www.devze.com 2023-03-30 08:25 出处:网络
If I have a variable x = \"\" And I check for the following condition if x !开发者_如何学Python= 0

If I have a variable x = ""

And I check for the following condition if x !开发者_如何学Python= 0

Is it evaluated as false across all the browsers ?

Why is 0 treated the same as "" ?


When you use the == operator JavaScript attempts to convert both operands to the same type for comparison. When you have a string and a number it attempts to convert the string to a number. "" converts to 0, giving you this result.

Because of this behaviour many people chose to use the === and !== operators instead. Their operands must be the same type to be considered equal.


Because both 0 and '' are evaluated like this:

0 == false  //true
'' == false //true

Use === to check properly


Is "" that when casted is egual to 0:

"" != 0 -> string != int -> (int)string != int -> int != int

0

精彩评论

暂无评论...
验证码 换一张
取 消