Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to split arguments in to value in NodeJS?

Is it possible to do something like this?

function one(){
    two(arguments)
}

function two(a, b){
    console.log(a);
    console.log(b);
}

one('a', 'b');
like image 300
user1692333 Avatar asked Dec 01 '25 05:12

user1692333


1 Answers

Yes, use apply()

function one(){
    two.apply(null, [].slice.call(arguments))
}

Some older engines insist upon receiving an array as the second parameter to apply(). Unfortunately, arguments is an array-like object. That's to say, it's not truly an array but it has a length property and numeric indices in addition to callee and caller properties. So, we call Array.slice() in order to get a plain array to pass to apply().

That said, V8 (used by node.js) should be fine without such translation:

function one(){
    two.apply(null, arguments)
}

That was my fault, I missed the node.js tag.

like image 173
canon Avatar answered Dec 03 '25 18:12

canon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!