0

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?

4
  • Yes it's perfectly fine to pass different types, and the code you posted does not generate any error when you pass (1, "b", 3, "d"). Commented Feb 20, 2014 at 15:35
  • It works fine here. Could you provide a way to reproduce your problem? Commented Feb 20, 2014 at 15:35
  • 2
    It works see jsfiddle.net/LKZkH Commented Feb 20, 2014 at 15:36
  • Just my Test.expect return that message, but now i see it works. Ty for the help. Commented Feb 20, 2014 at 15:45

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.