The trickiness comes when I try to typecast something to a number like this:
var testString:String = "77";
trace( testString as Number );
// Traces null
var testNumber:Number = testString as Number;
trace( testNumber );
// Traces 0
This is a problem because this particular syntax will always return a null, which sometimes leads me to spend too much time tracing this down because sometimes I'm writing code that handles null values gracefully. Anyways, the proper way is:
var testString:String = "77";
trace( Number(testString) );
// Traces 77
Because you're actually utilizing conversion functions for Top Level classes like Number, String, Array, which override casting one might do with the Number(object) kind of syntax when using non-top level classes. These can also lead to unexpected results if you aren't careful.
No comments:
Post a Comment