开发者

Javascript 0 Vs Blank

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜