我想调用带有可变长度参数的console.log函数
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..
}
}
Run Code Online (Sandbox Code Playgroud)
有没有(更短的)其他方式,请注意我不想要这个解决方案(因为x对象(参数或数组)的其他方法将被输出.
console.log(p,x);
Run Code Online (Sandbox Code Playgroud)
是的,你可以使用 apply
console.log.apply(console, /* your array here */);
Run Code Online (Sandbox Code Playgroud)
完整代码:
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);
}
Run Code Online (Sandbox Code Playgroud)