Skip to main content
June 5, 2009
Answered

Finding out if the object is an ARRAY type?

  • June 5, 2009
  • 2 replies
  • 789 views

Hello Everyone,

How can I find out if it is an Array object that is being passed? I usually rely upon the "typeof()" which returns the primitive type. But I am unable to find out if the passed value is an Array. I wrote a simple function which return the type:

function getType(p:object)

{

     return typeof(p);

}

So I then wrote a function with switch statement:

function getArray(p:Object)
{
    switch(typeof(p))
    {
        case 'string':
        return "STRING";
        break;
       
        case 'boolean':
        return "BOOLEAN";
        break;
       
        case 'object':
        return "OBJECT";
        break;
    }

I would highly apprecite your input in this.

Thanks you.

This topic has been closed for replies.
Correct answer kglad

use the is operator:

if(p is Array){

} else if(p is Object){

} etc

2 replies

Inspiring
June 5, 2009

If you want a more generic way to get a string representation of the class type, you can also use flash.utils.describeType:


var test:Array=[new Sprite(),new Array("[array example]"), new Object(),1.45,"hello world"];


function quickDescription(obj:*):String{
    var desc:XML =flash.utils.describeType(obj);
    var type:String=desc.@name;
    if (type.indexOf("::")>-1) type=type.split("::")[1];
    var baseClass:String=desc.@base;
    if (baseClass.length && baseClass.indexOf("::")>-1) baseClass=baseClass.split("::")[1];
    return (baseClass.length? type+" from a base class of "+baseClass : type);

}

for each(var item:Object in test) trace (item +" is "+quickDescription(item))

/* outputs:
[object Sprite] is Sprite from a base class of DisplayObjectContainer
[array example] is Array from a base class of Object
[object Object] is Object
1.45 is Number from a base class of Object
hello world is String from a base class of Object
*/

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
June 5, 2009

use the is operator:

if(p is Array){

} else if(p is Object){

} etc