Adi Drumea

Tuesday, November 27, 2007

[Javascript] typeof

Today i needed a way to check the real type of an object in javascript. Since typeof always returns 'object' for Date and Array objects, i needed a typeof routine that would return 'array' or 'date' (needed for json encoding). Here is a simple method to detect if an object is an Array instance or a Date instance:

function objectIsArray(o) {
if (o === null)
return false;
return o.constructor == (new Array).constructor;
}

The constructor function is always defined for arrays. Two functions return equal if and only if they're the same function.

4 Comments:

Post a Comment

<< Home