Difference between conditionals
Just wanted to know if someone can explain the difference between these two conditionals:
if ( !object )
if ( object == null )
where objec开发者_开发问答t is an instance of a user-defined class.
I'm sure that these two cannot be used in an interchangeable manner, or are they?
Thanks.
The effect is in practice the same, so I guess you could say they're interchangeable.
In a boolean context (such as a conditional), an expresion is evaluated to either true or false.
In Actionscript 3.0, the following values evaluate to false:
- false
- null
- 0
- NaN
- "" (the empty string)
- undefined
- void
Everything else evaluates to true.
A reference to an user-defined class instance can either be null or not null.
So, in this case:
if ( object == null )
Obviously, the condition is met only if object is null.
In this other case:
if ( !object )
The expression object
will evaluate to false if object
is null
. If it is null
, the expression is false. Since this is in turn negated, the final value will be true and so the condition will be satisfied. So, just like in the first case, if object
is null, the condition is met. And like in the first case, again, if object
is not null, the condition is not met.
There's no other option if your variable is typed to a user-defined class; such a variable can only contain a valid reference or null; i.e. it can't hold any value evaluable to false in a boolean context, except for null; so, again, it's either null or not null. Which is why both code samples have the same effect.
The first is making a boolean comparison. If the object is false, the not(!) operation will make the condition true, if the object has a value other than false the statement will fail.
The second conditional is evaluating if the object has the value of null or not.
The reason these may be interchangeable is that various languages allow some equivalence between 0, false, null (or "\0") and other values of similar meaning.
I do not know actionscript, but testing equivalence of false, null, 0 etc., or reading the docs on boolean values, will be of some benefit.
Sure not :) The first one means that the proposition is true only if different from the object; The second one is true only if the object equals to null.
"!" means "is not the object" "==" means that the the object has to have the value equal to the one at the right of the symbol
精彩评论