最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript calling console.log function with variable length - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 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);
}
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(', '));
}
发布评论

评论列表(0)

  1. 暂无评论