2

i want to call console.log function with variable length argument

function debug_anything() { var x = arguments; var p = 'DEBUG from ' + (new Error).stack.split("\n")[2]; switch(x.length) { case 0: console.log(p); break; case 1: console.log(p,x[0]); break; case 2: console.log(p,x[0],x[1]); break; case 3: console.log(p,x[0],x[1],x[2]); break; case 4: console.log(p,x[0],x[1],x[2],x[3]); break; // so on.. } } 

is there any (shorter) other way, note that i do not want this solution (since other methods from the x object (Argument or array) would be outputted.

console.log(p,x); 
1
  • 1
    See my answer over here. stackoverflow.com/a/14667091 Regards, Hans Commented Feb 2, 2013 at 22:46

3 Answers 3

5

Yes, you can use apply

console.log.apply(console, /* your array here */); 

The full code:

function debug_anything() { // convert arguments to array var x = Array.prototype.slice.call(arguments, 0); var p = 'DEBUG from ' + (new Error).stack.split("\n")[2]; // Add p to the beggin of x x.unshift(p); // do the apply magic again console.log.apply(console, x); } 
Sign up to request clarification or add additional context in comments.

4 Comments

ERROR! Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type
@Kiswono Prayogo: because of .call, not .apply. And console, not this
@KiswonoPrayogo I do a better example to fix it.
@KiswonoPrayogo sorry, but for log works was needed to pass console as it context. It will work now, you don't need to convert arguments to array if you want, but if you are using a array is better that must be an array hehe
3
function debug_anything() { var x = arguments; var p = 'DEBUG from ' + (new Error).stack.split("\n")[2]; console.log.apply(console, [p].concat(Array.prototype.slice.call(x))); } 

1 Comment

+1 I like your code style, do the same as my one, but is stylish!
1

Just join the array

function debug_anything() { var x = Array.prototype.slice.call(arguments, 0); var p = 'DEBUG from ' + (new Error).stack.split("\n")[2]; console.log(p, x.join(', ')); } 

1 Comment

ERROR: Uncaught TypeError: Object #<Object> has no method 'join'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.