473,508 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to check typeof arguments?

I have this generic function (JavaScript newbie here, so don't think I am going to impress
you):

function blah()
{
var container = '';
for(var i = 0; i < arguments.length; i++)
{
container += arguments[i] + '\n';
}
alert(container);
}

Now, if I call this like:

blah('Me', 'Myself', 'I');

I get:

ALERT (you know, the alert dialog)
Me
Myself
I

However, if I call it with an array:

var arr_obj = new Array('Me', 'Myself', 'I');
blah(arr_obj);

I get:

ALERT
Me,Myself,I

I tried checking the type of the arguments object but no matter what is passed, arguments
always has a type of 'object'.

Is there something I am missing as to how to check whether or not I passed it an array or
a normal comma-separated string of values?

Also, forgive me if I am missing some fundamental thing here. Thanks!

-Lost
Jan 27 '07 #1
11 4039
VK
I tried checking the type of the arguments object
but no matter what is passed, arguments always has a type of 'object'.
arguments object is - but not arguments passed to function.

function f() {
alert(typeof arguments[0]);
}

f('foobar'); // alerts 'string'
Is there something I am missing
when you do
var something+= arguments[0] + '\n';
then you call toString method for arguments[0]. If you have passed an
array reference as argument, toString for array object is called. And
for arrays toString returns comma-separated string of values.
as to how to check whether or not I passed it an array or
a normal comma-separated string of values?
if (typeof arguments[i] == 'string') {
// string argument
}
else if (arguments[i] instanceof Array) {
// array argument
}

Please not that you cannot uniform the check by using instanceof in
both cases. Implicit and explicit string constructors in JavaScript
are two separate entities, so say
(arguments[i] instanceof String) will be true only for explicit string
objects created over new String("something") - something you very
rarely want to do.

Jan 27 '07 #2
"-Lost" <sp****************@REMOVEMEcomcast.netwrote in
news:wo******************************@comcast.com:
I have this generic function (JavaScript newbie here, so don't think I
am going to impress you):

function blah()
{
var container = '';
for(var i = 0; i < arguments.length; i++)
{
container += arguments[i] + '\n';
}
alert(container);
}

Now, if I call this like:

blah('Me', 'Myself', 'I');

I get:

ALERT (you know, the alert dialog)
Me
Myself
I

However, if I call it with an array:

var arr_obj = new Array('Me', 'Myself', 'I');
blah(arr_obj);

I get:

ALERT
Me,Myself,I

I tried checking the type of the arguments object but no matter what
is passed, arguments always has a type of 'object'.

Is there something I am missing as to how to check whether or not I
passed it an array or a normal comma-separated string of values?

Also, forgive me if I am missing some fundamental thing here. Thanks!
See this tutorial for typeof and dltypeof:
http://www.webreference.com/dhtml/column68/
Jan 27 '07 #3
-Lost wrote:
I have this generic function (JavaScript newbie here, so don't think I am going to impress
you):
[...]
I tried checking the type of the arguments object but no matter what is passed, arguments
always has a type of 'object'.

Is there something I am missing as to how to check whether or not I passed it an array or
a normal comma-separated string of values?
How the typeof operator works is specified in section 11.4.3 of the
ECMAScript Language specification. Depending on the expression
provided, it returns one of:

Type Result
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
String "string"
Object (native doesn’t
implement [[Call]]) "object"
Object (native and
implements [[Call]]) "function"
Object (host) Implementation-dependent
The only tricky part is that objects are split into plain objects and
function objects.

A javascript Array is an object constructed using the built-in Array
function object as a constructor, therefore typeof Array returns
'function'. A function's arguments object isn't a function, so typeof
arguments returns 'object'.

If you want to know more about an object, you can try the constructor
property but that can be inconsistent across browsers. It may be better
to use instanceOf.

var x = [];
alert(typeof x) // object
alert(x instanceof Array); // true
To determine whether arguments passed to a function are strings, numbers
or arrays, do something like:

function foo () {
var arg, args = arguments;
var len = args.length;

for (var i=0; i<len; i++){
arg = args[i];

if (typeof arg == 'string' || typeof arg == 'number'){
alert('arg ' + i + ' is a string or number');
} else if (arg instanceof Array){
alert('arg ' + i + ' is an Array');
} else if (arg instanceof Function){
alert('arg ' + i + ' is a Function');
}
}
}

foo( [], 6, 'blah', function(){} );
--
Rob
Jan 28 '07 #4
Thanks VK, Jim Land, and RobG! Great information from all three.

Now to absorb it all...

-Lost
Jan 28 '07 #5
dd
On Jan 27, 7:33 pm, "-Lost" <spam_ninjaREMOV...@REMOVEMEcomcast.net>
wrote:

Here's a version of blah that would do what you expect:

function blah() {
var ar=arguments.length==1?arguments.split(","):argume nts;
var container = '';
for(var i = 0; i < ar.length; i++)
{
container += ar[i] + '\n';
}
alert(container);
}

Jan 28 '07 #6


On Jan 28, 6:54 pm, "dd" <dd4...@gmail.comwrote:
On Jan 27, 7:33 pm, "-Lost" <spam_ninjaREMOV...@REMOVEMEcomcast.net>
wrote:

Here's a version of blah that would do what you expect:
Please don't top-post here, reply below trimmed quotes.
>
function blah() {
var ar=arguments.length==1?arguments.split(","):argume nts;
That will fail - the arguments object is not a string, it doesn't have
a split method. In most browsers, arguments is just an object with an
array-like length property and zero-indexed numeric property names.
In some browsers it is an Array object.
--
Rob

Jan 28 '07 #7
"RobG" <rg***@iinet.net.auwrote in message
news:11*********************@l53g2000cwa.googlegro ups.com...
>

On Jan 28, 6:54 pm, "dd" <dd4...@gmail.comwrote:
>On Jan 27, 7:33 pm, "-Lost" <spam_ninjaREMOV...@REMOVEMEcomcast.net>
wrote:

Here's a version of blah that would do what you expect:

Please don't top-post here, reply below trimmed quotes.
>>
function blah() {
var ar=arguments.length==1?arguments.split(","):argume nts;

That will fail - the arguments object is not a string, it doesn't have
a split method. In most browsers, arguments is just an object with an
array-like length property and zero-indexed numeric property names.
In some browsers it is an Array object.
--
Rob
This *would* work though:

function blah()
{
var arg_obj = String(arguments[0]);
var arg = (arguments.length == 1) ? arg_obj.split(',') : arguments;
var container = '';
for(var i = 0; i < arg.length; i++)
{
container += arg[i] + '\n';
}
alert(container);
}

I wonder though, should I explicitly handle the scenarios? That is, when arguments[0] is
an object (possible array), should I test for it then convert it to a string? Otherwise,
leave arguments[0] alone?

-Lost
Jan 28 '07 #8
RobG wrote:
<snip>
... . In most browsers, arguments is just an object with an
array-like length property and zero-indexed numeric property
names. In some browsers it is an Array object.
The specification asserts that the - arguments - object should have the
original - Object.prototype - as its prototype, so it should not inherit
any methods or properties of arrays, and if it does that is an
implementation bug.

Richard.

Jan 28 '07 #9


On Jan 29, 7:14 am, "Richard Cornford" <Rich...@litotes.demon.co.uk>
wrote:
RobG wrote:<snip>
... . In most browsers, arguments is just an object with an
array-like length property and zero-indexed numeric property
names. In some browsers it is an Array object.

The specification asserts that the - arguments - object should have the
original - Object.prototype - as its prototype, so it should not inherit
any methods or properties of arrays, and if it does that is an
implementation bug.
In Opera, the arguments object is an Array as indicated by the
following test:

function foo(){ alert(arguments instanceof Array);}
foo(); // Alerts "true" in Opera, "false" in other browsers

They probably consider it a feature rather than a bug. :-) As far
as I can tell, Waldemar Horwat[1] of Netscape suggested that arguments
be an Array in JavaScript 2.0 back in 2003.
1. <URL: http://www.mozilla.org/js/language/js20/core/
functions.html#arguments-array >

--
Rob

Jan 28 '07 #10
"RobG" <rg***@iinet.net.auwrote in message
news:11*********************@v33g2000cwv.googlegro ups.com...
On Jan 29, 7:14 am, "Richard Cornford" <Rich...@litotes.demon.co.uk>
wrote:
>RobG wrote:<snip>
... . In most browsers, arguments is just an object with an
array-like length property and zero-indexed numeric property
names. In some browsers it is an Array object.

The specification asserts that the - arguments - object should have the
original - Object.prototype - as its prototype, so it should not inherit
any methods or properties of arrays, and if it does that is an
implementation bug.

In Opera, the arguments object is an Array as indicated by the
following test:

function foo(){ alert(arguments instanceof Array);}
foo(); // Alerts "true" in Opera, "false" in other browsers

They probably consider it a feature rather than a bug. :-) As far
as I can tell, Waldemar Horwat[1] of Netscape suggested that arguments
be an Array in JavaScript 2.0 back in 2003.
1. <URL: http://www.mozilla.org/js/language/js20/core/
functions.html#arguments-array >
Baring in mind I know very little at this point, I would also imagine that Opera considers
it a feature as opposed to a bug.

The fact that Opera supports a tremendous amount of DOM features as exhibited here:

http://www.w3.org/2003/02/06-dom-support.html

....makes me think they are keenly interested in supporting the standards, regardless. As
much as I love Opera I cannot abandon Firefox. Don't ask me why.

However, my recent musings (and the very informative responses I received) make me think
that arguments should either be a String or an Array based solely upon what was given to
said function. I realize of course that arguments is an object, as it has properties, but
still think it could be a little friendlier in its implementation.

That may just be a(n uninformed) newbie point of view. *shrugs*

-Lost
Jan 29 '07 #11
RobG wrote:
On Jan 29, 7:14 am, Richard Cornford wrote:
>RobG wrote:<snip>
>>... . In most browsers, arguments is just an object with an
array-like length property and zero-indexed numeric property
names. In some browsers it is an Array object.

The specification asserts that the - arguments - object should
have the original - Object.prototype - as its prototype, so it
should not inherit any methods or properties of arrays, and if
it does that is an implementation bug.

In Opera, the arguments object is an Array as indicated by the
following test:

function foo(){ alert(arguments instanceof Array);}
foo(); // Alerts "true" in Opera, "false" in other browsers
I know, it is a bug.
They probably consider it a feature rather than a bug. :-)
They would be wrong if they did. If they claim to be implementing ECMA
262 3rd Ed. then the prototype if the - arguments - object is specified
and doing anything other is a bug. Granted it is not a particularly
important bug as with everyone expecting the - arguments - object not to
be an array they are unlikely to treat it as such.
As far as I can tell, Waldemar Horwat[1] of Netscape suggested
that arguments be an Array in JavaScript 2.0 back in 2003.
It is a pity that next generation of javascript looks like an attempt to
make it more Java-like. It would probably be a better idea to not to go
in that direction and instead fix some of the ambiguities in the existing
specification. Making the - arguments - object into an array object (or
at least an array-like, as there is a specified linkage between then
'array index' properties of the - array - object and the formal parameter
properties of the Variable object) may be considered such an improvement.

Richard.

Jan 29 '07 #12

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

Similar topics

8
10003
by: Robert Mark Bram | last post by:
Hi All! I have the following code in an asp page whose language tag is: <%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%> // Find request variables. var edition = Request.Form ("edition"); var...
26
9566
by: JGH | last post by:
How can I check if a key is defined in an associative array? var users = new array(); users = "Joe Blow"; users = "John Doe"; users = "Jane Doe"; function isUser (userID) { if (?????)
23
25593
by: Randell D. | last post by:
Folks, I have written some scripting tools that are compatable with alot of my pages - For example, I've created a script that will check to ensure certain form fields that require data, are...
7
9934
by: Mark Miller | last post by:
I am using Reflection.Emit to dynamically build a class. A method of the class to be built requires a Parameter of type "Type". But I don't know how to use Emit to pass a call of "typeof()" to the...
10
19957
by: Patrick B | last post by:
Is there a way to check if a certain variable is an enum? Example code: public enum MyEnum { Monday, Tuesday, Wednesday } public void MyMethod()
4
1634
by: Peter Kirk | last post by:
Hi is there a difference between "this.GetType()" and typeof(MyClass)? The only reason I ask is that we are using log4net in a project, and we give the Loggers names based on the class name....
3
5737
by: Stefan | last post by:
Hi, i'm using code below to check if control is a button how can i check for more types of controls(like checkbox,...) in one 'nice piece" of code I tried to make a select case with 'typeof...is'...
2
2327
by: Andrew Robinson | last post by:
I am guessing there is a simple solution but given a type T, how can I check for nullability? how can I accomplish the following? bool nullable = typeof(int).IsNullable; // false bool...
11
12792
by: Einar Værnes | last post by:
Hi. I am trying to programatically decide which type a new object should have, but the typeof-function is apparently not the answer, as the following code will not compile. class...
0
7231
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,...
0
7133
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...
0
7336
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,...
0
4724
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3214
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...
0
3198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1568
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 ...
1
773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
435
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...

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.