19

I want to do something like this in Actionscript 3:

if(variable is Object) ...;
else ...;

Where variable could be a String(), Number(), Array(), Object()...

Currently the above check returns true for all of these types, which makes sense. I only want it to return true for objects made with new Object(), however.

Any help would be much appreciated!

Tapio Saarinen
  • 2,499
  • 3
  • 20
  • 18

4 Answers4

35

You should try to use this functions - getQualifiedClassName and typeof. Here's a code showing how they behave for different data types you've listed, see the difference for the Array and Numbers especially:

Code:

var o = new Array();                
trace ("var o = new Array()");
trace (getQualifiedClassName(o));
trace (typeof(o));      
var o = new Object();   
trace ("var o = new Object();");
trace (getQualifiedClassName(o));
trace (typeof(o));
var o = new String();
trace ("var o = new String()");
trace (getQualifiedClassName(o));
trace (typeof(o));
var o = new Number()
trace ("var o = new Number()");
trace (getQualifiedClassName(o));
trace (typeof(o));              
var o = 3.14;
trace ("var o = 3.14");
trace (getQualifiedClassName(o));
trace (typeof(o));

Result:

var o = new Array()
Array
object
var o = new Object();
Object
object
var o = new String()
String
string
var o = new Number()
int
number
var o = 3.14
Number
number

I assume getQualifiedClassName would be what you're looking for, which is in the flash utils package:

import flash.utils.getQualifiedClassName;
Matt Lacey
  • 8,227
  • 35
  • 58
Robert Bak
  • 4,246
  • 19
  • 20
  • Yep, I actually found out about getQualifiedClassName shortly after, and it is indeed what I was looking for. Thanks for the reply! – Tapio Saarinen Dec 12 '09 at 11:49
5

Try something based around one of these:

if (variable.constructor.toString().match(/object/i) == 'Object')

if (variable.constructor.toString().indexOf("Object") != -1)

If the object is an Object() the constructor string will be something like

function Object() { ... }

so you can check for that.

Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
3

You can also use getQualifiedSuperclassName which returns null for the Object type as it doesn't have a super class:

public static function isObject( obj:* ):Boolean
{
    if ( obj == null )
        return false;
    return ( getQualifiedSuperclassName( obj ) == null );
}
divillysausages
  • 7,883
  • 3
  • 25
  • 39
-1

here you go, try this..

var ob:Object = new Object();

trace(ob); //[object Object]
trace(typeof(ob) == "object"); //true

if(typeof(ob) == "object"){
    //true
}else{
    //false
}
K-G
  • 2,799
  • 4
  • 26
  • 42