【问题标题】:javascript calling console.log function with variable lengthjavascript调用具有可变长度的console.log函数
【发布时间】:2012-12-19 14:44:57
【问题描述】:

我想调用带有可变长度参数的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..
  }
}

有没有(更短的)其他方式, 请注意,我不想要这个解决方案 (因为会输出 x 对象(参数或数组)的其他方法。

console.log(p,x);

【问题讨论】:

标签: javascript


【解决方案1】:

是的,您可以使用apply

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

完整代码:

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);
}

【讨论】:

  • 错误!未捕获的 TypeError:Function.prototype.apply:参数列表类型错误
  • @Kiswono Prayogo:因为.call,而不是.apply。还有console,而不是this
  • @KiswonoPrayogo 我做了一个更好的例子来解决它。
  • @KiswonoPrayogo 抱歉,但对于日志工作,需要将 console 作为上下文传递。它现在可以工作了,如果需要,您不需要将参数转换为数组,但是如果您使用数组更好,则必须是数组呵呵
【解决方案2】:
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 我喜欢你的代码风格,和我的一样,但是很时尚!
【解决方案3】:

只需join 数组

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(', '));
}

【讨论】:

  • ERROR: Uncaught TypeError: Object # has no method 'join'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 2022-09-23
  • 2013-08-27
  • 1970-01-01
相关资源
最近更新 更多