473,669 Members | 2,504 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.lengt h; 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 4058
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("somethi ng") - something you very
rarely want to do.

Jan 27 '07 #2
"-Lost" <sp************ ****@REMOVEMEco mcast.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.lengt h; 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_ninjaREMO V...@REMOVEMEco mcast.net>
wrote:

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

function blah() {
var ar=arguments.le ngth==1?argumen ts.split(","):a rguments;
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.c omwrote:
On Jan 27, 7:33 pm, "-Lost" <spam_ninjaREMO V...@REMOVEMEco mcast.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.le ngth==1?argumen ts.split(","):a rguments;
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.ne t.auwrote in message
news:11******** *************@l 53g2000cwa.goog legroups.com...
>

On Jan 28, 6:54 pm, "dd" <dd4...@gmail.c omwrote:
>On Jan 27, 7:33 pm, "-Lost" <spam_ninjaREMO V...@REMOVEMEco mcast.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.le ngth==1?argumen ts.split(","):a rguments;

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(argument s[0]);
var arg = (arguments.leng th == 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.prototyp e - 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...@litote s.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.prototyp e - 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

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

Similar topics

8
10016
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 language = Request.Form ("language"); Response.Write("Edition is type &quot;" + (typeof edition) + "&quot; and value &quot;" + edition + "&quot;<br>");
26
9610
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
25616
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 completed. In order for this to work, I must pass it the form name, and the field names (input tag names). Sometimes I copy/paste the syntax from one page to another and I might forget to change the form name, or an input tag name passed in the
7
9961
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 method. The method could look like this: public void myDynamicMethod(Type type){ //.....do something with the Type passed in....... }
10
19976
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. For example, some people use: ILog log = LogManager.GetLogger(typeof(Finder).ToString()); others use:
3
5760
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' but i didn't get it work If Not TypeOf ctr Is Button Then AddHandler ctr.LostFocus, AddressOf meLostFocus
2
2336
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 nullable = typeof(int?).IsNullable; // true bool nullable = typeof(string).IsNullable; // true Thanks for any help.
11
12809
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 AbstractClass:Object { } class DerivedClass1 : AbstractClass { } class DerivedClass2 : AbstractClass { }
0
8465
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
8383
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
8658
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7407
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6210
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
5682
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2797
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
2
2032
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1788
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.