- Nov 11, 2009 | 0 comment(s)
- Posted in: Flash
AS3 version of PHP’s empty() function
When working in PHP I often find the empty() function handy for checking whether a variable is empty or has a zero value. It’s great because I can use it to check different types of variables: boolean, string, array and any variable that is null, or declared but without a value in the class. So I decided to write a similar function in AS3 for my Flash projects. Here it is:
public static function empty(variable:*) : Boolean {
var isEmpty:Boolean;
if (variable == null || variable == undefined) {
isEmpty = true;
}
else if (variable is String) {
var str:String = variable.replace(/^\s+|\s+$/g, '');
isEmpty = (str.replace(/\s+/g, ' ') == "" || variable == "" || variable == "0" || variable == "false");
}
else if (variable is Number || variable is int || variable is uint) {
isEmpty = (variable == 0);
}
else if (variable is Array) {
isEmpty = (variable.length == 0);
}
else if (variable is Boolean) {
isEmpty = (variable == false);
}
return isEmpty;
}
Similar to the PHP version but with some extras, the following things are considered to be empty and will return false:
- NULL
- UNDEFINED
- 0 (0 as a Number, int or uint)
- “” (an empty String)
- ” ” (a String containing only whitespace)
- “0″ (0 as a String)
- “false” (false as a String)
- FALSE (Boolean)
- Array() (an empty array or an array of zero length)
- var myVar:*; (a variable declared, but without a value)
If you have any suggestions or improvements to this, let me know and I’ll update it.
- Tweet this post (will automatically use the short url below)
- Short url for this post: http://bit.ly/BJirV
Ben Kanizay
0 comment(s)
Track this comments via RSS 2.0 feed. Feel free to post the comment, or trackback from your web site.