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);
Kokizzu
  • 24,974
  • 37
  • 137
  • 233
  • 1
    See my answer over here. http://stackoverflow.com/a/14667091 Regards, Hans –  Feb 02 '13 at 22:46

3 Answers3

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);
}
Gabriel Gartz
  • 2,840
  • 22
  • 24
  • ERROR! Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type – Kokizzu Jan 05 '13 at 06:53
  • 1
    @Kiswono Prayogo: because of `.call`, not `.apply`. And `console`, not `this` – zerkms Jan 05 '13 at 06:53
  • @KiswonoPrayogo I do a better example to fix it. – Gabriel Gartz Jan 05 '13 at 06:55
  • 1
    @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 – Gabriel Gartz Jan 05 '13 at 07:01
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)));
}
Lyn Headley
  • 11,368
  • 3
  • 33
  • 35
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(', '));
}
epoch
  • 16,396
  • 4
  • 43
  • 71