suuuzi
suuuzi

Reputation: 622

Javascript multiple arguments and different data types in a function

I use arguments to allow multiple parameters in a function, like this:

  function foo(){
     for (var i = 0; i < arguments.length; i++) {
        alert(arguments[i]);         
     }
  }

Passing foo(1, 2, 3, 4) = OK

But i need to know if it is possible to use various types of parameters, like foo(1, "b", 3, "d"). I get Value is not what was expected when i try.

Any suggestion?

Upvotes: 0

Views: 1522

Answers (2)

alfonsob
alfonsob

Reputation: 635

Also to add, a solid way to distinguish your function arguments between built in javascript object classes (Date, Array, RegExp etc) is to use comparisons like:

Object.prototype.toString.call(arguments[0]) === '[object Date]'
Object.prototype.toString.call(arguments[0]) === '[object RegExp]'

and so on, using a similar construct to @am1r_5h answer above

Upvotes: 0

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

you need to handle this by yourself in your foo function, for example if you expect a function as first argument, you need to check if it is, at first of foo:

if(typeof arguments[0] != "function")
    throw new Error("unexpected argument")

or if you need a number as first argument:

if(typeof arguments[0] != "number")
    throw new Error("unexpected argument")

or try to convert it to a number first, like:

var o = parseInt(arguments[0])
if(Number.isNaN(o))
    throw new Error("unexpected argument")

Upvotes: 1

Related Questions