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);
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);
Share
Improve this question
asked Jan 5, 2013 at 6:44
KokizzuKokizzu
26.9k40 gold badges149 silver badges253 bronze badges
1
- 1 See my answer over here. stackoverflow./a/14667091 Regards, Hans – user2036140 Commented Feb 2, 2013 at 22:46
3 Answers
Reset to default 5Yes, 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);
}
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)));
}
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(', '));
}