Utility Functions For AS3 Objects
/**
* Count the properties in an object
* @param obj Object to count the properties of
* @return The number of properties in the specified object. If the
* specified object is null, this is 0.
* @author Jackson Dunstan
*/
public static function numProperties(obj:Object): int
{
var count:int = 0;
for each (var prop:Object in obj)
{
count++;
}
return count;
}
/**
* Check if an object has any properties
* @param obj Object to check for properties
* @return If the specified object has any properties. If the
* specified object is null, this is false.
* @author Jackson Dunstan
*/
public static function hasProperties(obj:Object): Boolean
{
for each (var prop:Object in obj)
{
return true;
}
return false;
}
/**
* Check if the properties of an object are all the same
* @param obj Object whose properties should be checked
* @param type Type to check the object's properties against
* @return If all of the properties of the specified object are of the
* specified type
* @author Jackson Dunstan
*/
public static function isUniformPropertyType(obj:Object, type:Class): Boolean
{
for each (var prop:Object in obj)
{
if (!(prop is type))
{
return false;
}
}
return true;
}
/**
* Copy an object
* @param obj Object to copy
* @param into (optional) Object to copy into. If null, a new object
* is created.
* @return A one-level deep copy of the object or null if the argument
* is null
* @author Jackson Dunstan
*/
public static function copy(obj:Object, into:Object=null): Object
{
if (into == null)
{
into = {};
}
if (obj != null)
{
for (var o:* in obj)
{
into[o] = obj[o];
}
}
return into;
}
/**
* Convert the object to an array. Note that the order of the array is
* undefined.
* @param obj Object to convert
* @return An array with all of the properties of the given object or
* null if the given object is null
* @author Jackson Dunstan
*/
public static function toArray(obj:Object): Array
{
if (obj == null)
{
return null;
}
else
{
var ret:Array = [];
for each (var prop:Object in obj)
{
ret.push(prop);
}
return ret;
}
}
/**
* Convert the object to a string of form: PROP: VAL&PROP: VAL where:
* PROP is a property
* VAL is its corresponding value
* & is the specified optional delimiter
* @param obj Object to convert
* @param delimiter (optional) Delimiter of property/value pairs
* @return An string of all property/value pairs delimited by the
* given string or null if the input object or delimiter is
* null.
* @author Jackson Dunstan
*/
public static function toString(obj:Object=null, delimiter:String = "\n"): String
{
if (obj == null || delimiter == null)
{
return "";
}
else
{
var ret:Array = [];
for (var s:Object in obj)
{
ret.push(s + ": " + obj[s]);
}
return ret.join(delimiter);
}
}
作者:ywxgod
E-mail:给我发邮件
出处:http://ywxgod.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
E-mail:给我发邮件
出处:http://ywxgod.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号