array like objects
Mike Samuel
mikesamuel at gmail.com
Sat Dec 12 10:36:43 PST 2009
2009/12/12 Mike Wilson <mikewse at hotmail.com>:
> David-Sarah Hopwood wrote:
>> Mark S. Miller wrote:
>> > function isArrayLike(obj) {
>> > var len;
>> > return !!(obj &&
>> > typeof obj === 'object' &&
>> > 'length' in obj &&
>> > !({}).propertyIsEnumerable.call(obj, 'length') &&
>> > (len = obj.length) >>> 0 === len);
>> > }
Nits:
Array length is specified as being in [0, 0x8000_0000], but the range
of >>> is [0, 0x1_0000_0000).
On the String defect, we could repair that with
&& ({}).toString.call(obj) !== '[object String]'
Cons:
An extra function call in the likely case
Strings are arguable array-like
Pros:
Strings are inconsistently indexable : (new String('foo'))[0] is
undefined on IE 6
>> If you want to avoid side effects:
>>
>> function isArrayLike(obj) {
>> if (!obj || typeof obj !== 'object') return false;
>> var desc = Object.getOwnPropertyDescriptor(obj, 'length');
What will getOwnPropertyDescriptor do for proxied arrays under the
current proxy proposal?
>> if (desc) {
>> var len = desc.value;
>> return !desc.enumerable && (len === undefined || len >>>
>> 0 === len);
>> }
>> }
>
> An advantage with Mark's code is that it doesn't rely
> on ES5 API. I think it's good to establish a standard
> for array-likeness that can be matched by ES3 code as
> well.
>
> Best regards
> Mike
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
More information about the es-discuss
mailing list