现在,如果您不关心从 console.log("this", "that", "and the other")获得的 一样输出,只要您能看到那里有什么,那么只需使用 console.log(arguments);(arguments是传递到函数中的所有参数的内置标识符)。但是如果你想复制精确的输出,你最终会做这样的事情:
function f() {
var a = arguments;
if (typeof console != "undefined" && console.log) {
if (console.log.apply) {
// It has Function#apply, use it
console.log.apply(console, arguments);
} else {
// Ugh, no Function#apply
switch (a.length) {
case 0: console.log(); break;
case 1: console.log(a[0]); break;
case 2: console.log(a[0], a[1]); break;
case 3: console.log(a[0], a[1], a[2]); break;
case 4: console.log(a[0], a[1], a[2], a[3]); break;
case 5: console.log(a[0], a[1], a[2], a[3], a[4]); break;
default:
throw "f() only supports up to 5 arguments";
}
}
}
}
这太丑陋了。
* ES5添加了 约束函数,这是通过绑定将其 this值附加到它们的函数:
// Normal function
function foo() {
console.log(this.name);
}
// Create a bound function:
var f = foo.bind(someObject);
T.J。 Crowder 的回答帮助我解释和解决了我在重定向 console.log输出时遇到的一个问题,但是他对“ no Function # application”情况的解决方案似乎武断地限制了许多用例。
我像这样重写了他的代码,这样更干净,更实用:
function f() {
var a = arguments;
if (typeof console != "undefined" && console.log) {
if (console.log.apply) {
// It has Function#apply, use it
console.log.apply(console, arguments);
} else {
// Ugh, no Function#apply
var output = '';
for (i=0;i<arguments.length;i++) {
output += arguments[i] + ' ';
}
console.log(output);
}
}
}