Javascript: Pass array as optional method args

Posted by Dave Paroulek on Stack Overflow See other posts from Stack Overflow or by Dave Paroulek
Published on 2010-05-31T14:07:04Z Indexed on 2010/05/31 14:12 UTC
Read the original article Hit count: 391

Filed under:
|

console.log takes a string and replaces tokens with values, for example:

console.log("My name is %s, and I like %", 'Dave', 'Javascript')

would print:

My name is Dave, and I like Javascript

I'd like to wrap this inside a method like so:

function log(msg, values) {
  if(config.log == true){
    console.log(msg, values);
   }
 }

The 'values' arg might be a single value or several optional args. How can I accomplish this?

If I call it like so:

 log("My name is %s, and I like %s", "Dave", "Javascript");

I get this (it doesn't recognize "Javascript" as a 3rd argument):

 My name is Dave, and I like %s

If I call this:

 log("My name is %s, and I like %s", ["Dave", "Javascript"]);

then it treats the second arg as an array (it doesn't expand to multiple args). What trick am I missing to get it to expand the optional args?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery