"Aaron Gray" <> writes:
> I know this has probably been argued to death, but I am going to raise it
> fresh again, and basically lets have an unofficial 'isArray()' contest that
> we can hopefully put it to rest as best as we can.
Is there a setting where
obj instanceof Array
fails to detect an Array?
....
> Prototype for all its "failings" extends object
That's one failing right there

I thought they stopped doing that in later versions?
> and provides :-
>
> Object.extend(Object, {
> isArray: function(object) {
> return object != null && typeof object == "object" &&
> 'splice' in object && 'join' in object;
Sigh. Feature detection is good for detecting features. This is detection
by inference. This is as bad as
var isIE = document.all ? 1 : 0;
(ok, slightly better, the isIE example has more bad points than it has
keywords)
> So checking of non null and splice and join maybe better than just checking
> for push.
"maybe" is the operative word. I.e., it's shooting blind and hoping to
be lucky.
> So something like :-
>
> function isArray( o) { return o != null && typeof o == "object" &&
> 'push' in o }
>
> But I am not sure when 'in' was actually introduced.
JScript 5.6
JavaScript 1.4
Same versions as "instanceof", btw.
> function isArray( o) { return o != null && typeof o == "object" &&
> typeof o.push == "function" }
>
> Would probably do best/better. This is what I have settled on for now.
And when we implement a stack:
function Stack() {}
Stack.prototype.push = function(o) {
this.head = {elem: o, next: this.head }
};
Stack.prototype.pop = function() {
var head = this.head;
if (head) {
var elem = head.elem;
this.head = head.next;
return elem;
}
};
it suddently qualifies as an array?
An object is an Array if it inherits Array.prototype. That's the
prototype based definition of inheritance.
> Then there was the advice to use === rather than ==, but I dont know when
> that was introduced too, or whether it is really necessary as == works just
> as well AFAICS.
It's the same when dealing with objects. The "==" operator performs
type conversion in some cases, whereas the "===" requires both
operands to have the same type. When the operands are objects, they
work exactly the same,
> Any critisisms, advances, or advice ?
What problem are you trying to solve?
Why?
In any case, don't try to be clever. Either use "instanceof", or, if
it's *really* necessary to support ancient browsers, test simple
things:
function isArray(o) {
return o && o.constructor == Array;
}
It's easy to cheat, but anybody actively trying to cheat is going to
succeede anyway.
/L
--
Lasse Reichstein Nielsen
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'