2008年10月13日星期一

Distinguishing between JavaScript arrays and objects made easier

In JavaScript, it's not easy to distinguish between objects and arrays. The "typeof" operator returns "object" on both cases.  Using the "constructor" property doesn't work neither because the constructors of arrays from different browser windows or frames are not the same, which causes confusing behavior when an array is passed between browser windows as a argument.

In  Douglas Crockford's book "JavaScript: The Good Parts", he used a complex function as below:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};


In one of his recent blog posts, he mentioned that Mark Miller from Google used a simple approach to do the same thing.

Object.prototype.toString.apply(value) === '[object Array]'

I went through the ECMAScript specification and found out the following:

The value of the [[Class]] property is defined by this specification for every kind of built-in object. The value of the [[Class]] property of a host object may be any value, even a value used by a built-in object for its [[Class]] property. The value of a [[Class]] property is used internally to distinguish different kinds of built-in objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString.

The [[Class]] property of Array.prototype is "Array" and Object.prototype.toString uses this value to generate the output in the format "[object " + [[Class]] + "]" which results "[object Array]".

I think the new approach can help us a lot.

没有评论:

Technology changes life