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

javascript - Explode array elements into comma-separated arguments (Node.js) - Stack Overflow

programmeradmin0浏览0评论

Say I have a function that takes an arbitrary number of arguments (the last is callback):

xxx.create ('arg1', 'arg2', ..., 'arg10', callback) {
    ...
}

But it's ugly. I want to be able to extract the first few parameters and do something like:

var args = ['arg1', 'arg2', ..., 'arg10']
xxx.create (args.explode(), callback) {
    ...
}

Of course I can write a wrapper for xxx.create(), but I want it to be clean.

Thanks.

Say I have a function that takes an arbitrary number of arguments (the last is callback):

xxx.create ('arg1', 'arg2', ..., 'arg10', callback) {
    ...
}

But it's ugly. I want to be able to extract the first few parameters and do something like:

var args = ['arg1', 'arg2', ..., 'arg10']
xxx.create (args.explode(), callback) {
    ...
}

Of course I can write a wrapper for xxx.create(), but I want it to be clean.

Thanks.

Share Improve this question edited Sep 2, 2012 at 17:10 Pooria Azimi asked Mar 24, 2012 at 3:40 Pooria AzimiPooria Azimi 8,6435 gold badges31 silver badges41 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You're looking for Function.apply.

var args = ['arg1', 'arg2', ..., 'argN'];
xxx.create.apply(xxx, args.concat(callback)) {
    // ...
}

I used Array.concat so as to not mutate the original args array. If that's not a problem, either of these will suffice:

var args = ['arg1', 'arg2', ..., 'argN', callback];
xxx.create.apply(xxx, args) {
    // ...
}

// or

var args = ['arg1', 'arg2', ..., 'argN'];
args.push(callback);
xxx.create.apply(xxx, args) {
    // ...
}

Now, if you wanted to use a wrapper instead of exposing the Function.apply call:

function create_wrapper() {
    xxx.create(xxx, arguments);
}

// then

create_wrapper('arg1', 'arg2', ..., 'argN', callback);

will do the job.

The local arguments variable can help here:

foo = function(){
  // convert local 'arguments' object to array ...
  argsArray = Array.prototype.slice.call(arguments);

  // pop the callback off
  callback = argsArray.pop();

  // the callback alerts the remaining, variable-length arguments list
  callback(argsArray);
};

here's the jsfiddle: http://jsfiddle/K38YR/

发布评论

评论列表(0)

  1. 暂无评论