Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

typeof operator on Array variable gets 'object'

Status
Not open for further replies.

predamarcel

IS-IT--Management
Jan 6, 2003
268
RO
I have a javascript function in which one of the parameters SHOULD BE Array, not other Object.

In case if it is not an array I shoud do a quick return,
but I can not figure how to make the difference between the Array type and other Object type.
That because typeof var_array is object

Any ideas ?

___
____
 
Hi,

finnaly I've solved it.
I have write a function, myabe someone else will need it too, so I'll post the code here:

Code:
// return the Object Type
function getObjectType(obj)
{
        if ( typeof obj != 'object')
        {
                return typeof obj; // Not An Object

        };
        // if not constructor  return the  typeof obj
        if (obj.constructor == undefined)
        {
                return typeof obj;
        };

        var str = obj.constructor.toString();
        // Objects which has constructor
        str = str.split('function').join('');
        str = str.split('(');
        str = str[0];
        // trim the white spaces, ussing regexp
        re = /\s/g;
        new_str= str.replace(re,'');
        return new_str;
}

Looks like it works pretty cool, at least on FireFox 1.0 and IE 6.0
Code:
function myObj(x)
{
        this.property_x = x;
};
alert(getObjectType(1234));     // alerts 'number'
alert(getObjectType('abc'));    // alerts 'string'
my = new myObj('abc');
alert(getObjectType(my));       // alerts 'myObj'
alert(getObjectType(new Array("a", "b")));      // alerts 'Array'

___
____
 
Maybe this will help:
Code:
function getType(obj){
  return typeof(obj)=='object' ? obj.constructor==Array ? 'array' : 'object' : typeof(obj);
}

Adam
 
Actually, here it is a little more trimmed up:
Code:
function getType(obj){
  return obj.constructor==Array?'array':typeof(obj);
}

Adam
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top