473,748 Members | 2,231 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Its the isArray() function thing again

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.

I have found things that work perfectly well as long as you don't try them
on MSIE, ie adding Object and Array prototype isArray functions, thus :-

Object.prototyp e.isArray = function() { return false }
Array.prototype .isArray = function() { return true }

This falls down on builtin browser types in IE, so is no good.

The one version that I have seen is :-

function isArray( a) { return typeof a.push == "function" }

Prototype for all its "failings" extends object and provides :-

Object.extend(O bject, {
isArray: function(object ) {
return object != null && typeof object == "object" &&
'splice' in object && 'join' in object;
}
});

So checking of non null and splice and join maybe better than just checking
for push.

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.

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.

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.

Any critisisms, advances, or advice ?

Aaron
Jul 26 '08 #1
18 1849
On Jul 26, 3:03 pm, "Aaron Gray" <ang.use...@gma il.comwrote:
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.
In your actual application code, why are you ever having any trouble
knowing if a variable references an Array or not? If a function's API
states it should recieve an array argument, then just send it an array
argument. If it states it should receive a number, don't send it an
array. Be careful about bringing the baggage of focusing on type
checking and casting from languages like Java or C++ to your
JavaScript programming.
I have found things that work perfectly well as long as you don't try them
on MSIE, ie adding Object and Array prototype isArray functions, thus :-

Object.prototyp e.isArray = function() { return false }
Array.prototype .isArray = function() { return true }
Augmenting built in prototypes with generic names like "isArray" is
likely to collide in an envronment where multiple authors are writing
the JavaScript.

http://peter.michaux.ca/article/7979

This falls down on builtin browser types in IE, so is no good.

The one version that I have seen is :-

function isArray( a) { return typeof a.push == "function" }
That is a very wimpy test in general.

Prototype for all its "failings" extends object and provides :-
The quotation marks are not necessary.

Object.extend(O bject, {
isArray: function(object ) {
return object != null && typeof object == "object" &&
'splice' in object && 'join' in object;
}
});
Why they think writing

Object.isArray

is any different than

PrototypeJS.isA rray

I will never understand.

So checking of non null and splice and join maybe better than just checking
for push.

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.

function isArray( o) { return o != null && typeof o == "object" &&
typeof o.push == "function" }
So if I define a new object in JavaScript with a push function it will
pass your test. That is a very weak test.

Would probably do best/better. This is what I have settled on for now.

Then there was the advice to use === rather than ==, but I dont know when
that was introduced too,
http://pointedears.de/scripts/es-matrix/

or whether it is really necessary as == works just
as well AFAICS.
They are not the same. == and != do type coercion.

http://developer.mozilla.org/en/docs...ison_Operators

Any critisisms, advances, or advice ?
What's wrong with

if (obj instanceof Array) {
// do stuff
}

http://developer.mozilla.org/en/docs...nceof_Operator

Peter
Jul 26 '08 #2
"Aaron Gray" <an********@gma il.comwrites:
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(O bject, {
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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 26 '08 #3
Aaron Gray meinte:
But I am not sure when 'in' was actually introduced.
Then there was the advice to use === rather than ==, but I dont know when
that was introduced too
Before he does it:
http://pointedears.de/scripts/es-matrix/

Gregor
--
http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
http://web.gregorkofler.com ::: meine JS-Spielwiese
http://www.image2d.com ::: Bildagentur für den alpinen Raum
Jul 26 '08 #4
Aaron Gray meinte:
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.
Crockford suggests

var is_array = function(v) {
return v && typeof v === "object" && v.constructor === Array;
}

(wont work on arrays in other windows/frames)

or

var is_array = function(v) {
return v && typeof v === "object" && typeof v.length === "number" &&
typeof v.splice === "function" && !(v.propertyIsE numerable("leng th"));
}

(I suppose he took splice() because it's a relatively "rare" method)

Gregor
--
http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
http://web.gregorkofler.com ::: meine JS-Spielwiese
http://www.image2d.com ::: Bildagentur für den alpinen Raum
Jul 26 '08 #5
"Lasse Reichstein Nielsen" <lr*@hotpop.com wrote in message
news:4p******** **@hotpop.com.. .
"Aaron Gray" <an********@gma il.comwrites:
>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?
Don't know. But I had forgotten about 'instanceof Array' and thats exactly
what I need for this specific problem.

I think people use the other 'weaker' methods to allow inclusion of array
like objects as well as Arrays.
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;
}
Thomas is right, I really should read ECMA-262 properly.

Many thanks,

Aaron

Jul 26 '08 #6
On Jul 26, 3:36*pm, Lasse Reichstein Nielsen <l...@hotpop.co mwrote:
"Aaron Gray" <ang.use...@gma il.comwrites:
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?
There is: When obj is an Array in a different frame than the Array
constructor, it would be constructed via a different Array
constructor, and so obj instanceof Array would have to be false.
otherFrame.obj instanceof otherFrame.Arra y would be true, though.

Prototype for all its "failings" extends object
That was quite a long time ago.
That's one failing right there :)
I thought they stopped doing that in later versions?
Yes, they did.

Garrett

/L
Jul 26 '08 #7
On Jul 26, 4:52 pm, dhtml <dhtmlkitc...@g mail.comwrote:
"Aaron Gray" <ang.use...@gma il.comwrites:
Prototype for all its "failings" extends object

That was quite a long time ago.
They are still extending "Object" unnecessarily with function-valued
properties that could be added to any object. Adding them to "Object"
is just confusing, in my opinion. They also choose very generic names
in shared namespaces which is another problem of theirs.

http://www.prototypejs.org/api/object

Peter
Jul 27 '08 #8
On Jul 27, 9:52*am, dhtml <dhtmlkitc...@g mail.comwrote:
On Jul 26, 3:36*pm, Lasse Reichstein Nielsen <l...@hotpop.co mwrote:
"Aaron Gray" <ang.use...@gma il.comwrites:
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?

There is: When obj is an Array in a different frame than the Array
constructor, it would be constructed via a different Array
constructor, and so obj instanceof Array would have to be false.
otherFrame.obj instanceof otherFrame.Arra y would be true, though.
Prototype for all its "failings" extends object

That was quite a long time ago.
That's one failing right there :)
I thought they stopped doing that in later versions?

Yes, they did.
They stopped extending Object.prototyp e.

--
Rob
Jul 27 '08 #9
On Jul 26, 7:10*pm, RobG <rg...@iinet.ne t.auwrote:
On Jul 27, 9:52*am, dhtml <dhtmlkitc...@g mail.comwrote:
On Jul 26, 3:36*pm, Lasse Reichstein Nielsen <l...@hotpop.co mwrote:
"Aaron Gray" <ang.use...@gma il.comwrites:
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?
There is: When obj is an Array in a different frame than the Array
constructor, it would be constructed via a different Array
constructor, and so obj instanceof Array would have to be false.
otherFrame.obj instanceof otherFrame.Arra y would be true, though.
Prototype for all its "failings" extends object
That was quite a long time ago.
That's one failing right there :)
I thought they stopped doing that in later versions?
Yes, they did.

They stopped extending Object.prototyp e.
Ah, right that's what I was thinking about. Modifying
Object.prototyp e. That was very bad.

They still extend Object, which is not as bad. They add a clone()
method to Object, and clone is an ES3.1 Proposal. I asked Allen about
that

Object.clone is proposed for ES 3.1. I did mention it on the list, but
Allen was replying to a lot of responders, so he probably missed what
I wrote:

| It seems like Object.clone might create compatibility with existing
| code. There is already a widespread use of an Object.clone on the
web.
Garrett
--
Rob
Jul 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
3517
by: Laphan | last post by:
Hi All I'm using .getRows() with a local var array instead of doing a recursive loop so that I'm being a good ASP newvbie and closing my object i/o's (the recordset in this case) as quick as possible. My problem is that I can't seem to use this to complete good effect because the IsArray statement doesn't seem to work with a local var array that has or has not been populated with the .getRows() property.
33
10542
by: Matt Kruse | last post by:
I'm seeking the most robust and backwards-compatible (ie, no instanceof) isArray function. Here's what I have: function defined(o) { return typeof(o)!="undefined"; } function isArray(o) { // If these conditions aren't met, it certainly isn't an Array
8
6449
by: =?ISO-8859-1?Q?Norbert_P=FCrringer?= | last post by:
Hello again, I've got a type variable, e.g. Type type; Now I want to know whether the type represents an Array type (System.Array). type.IsArray results false because System.Array is an object, not an
0
8979
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8818
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9522
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9355
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6790
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4589
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4860
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3296
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.