Diff if statements

I have a lot of new things in as3 and I came up with a doublet, saying β€œif” roars, do the same?

public function get products(a:Object){ if(a){ // smtg } if(null!=a){ // smtg } } 
+4
source share
3 answers

No, they are not the same. Although in many cases they behave the same, there is a big difference that the first method evaluates the value, and the second just checks to see if the value is null.

You can see the difference with this example:

 function test ( a:Object ):void { if ( a ) trace( "A" ); if ( a != null ) trace( "B" ); } test( false ); // B test( "" ); // B test( 0 ); // B test( true ); // A & B // ... 

All values ​​that are evaluated as false will give different results.

+5
source

Note that the creature that is the object of a may not be null, but still false , so if (a) and if(a != null) could potentially give different results.

0
source

if (a) is different from if (a != null) .

The latter only checks the equality between a and null ; the first converts a to Boolean , and then checks to see if the result is true .

The first is essentially:

 if (Boolean(a)) ... 

What happens when a converted to a Boolean depends on the type of a . Here you can find the rules (see "Casting in Boolean"):

http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f87.html

In my tests, I found that if (a) is twice as fast as if (a != null) , even if a is an object, not a string or number.

0
source

Source: https://habr.com/ru/post/1338008/


All Articles