简体   繁体   中英

Can arrow functions incorporate the multiple arguments of a host function such as reduce?

I assume the answer to this question is no, but I'm not sure. Below is a reduce function , one is not using an arrow functions and one is. Is it possible to incorporate the second argument of the first into the arrow style ?

var s = arr.reduce(function(){

},0) // includes second argument

and........

var a = arr.reduce = () => {

} // ?

Yes, Arrow functions can work with multiple params, they just need to be added inside parenthesis.

var s = arr.reduce((accum, currVal) => accum + currVal, 0);
                   ^              ^                       : Multiple arguments to the Arrow function
                                                       ^^^: Second argument of the `reduce` function

Here, the second parameter to the Array#reduce can be passed normally. The arrow function( first parameter ) has no effect on how the second argument is passed.

The part of this code:

var s = arr.reduce(function(){

},0) // includes second argument

...that an arrow function would replace is purely this bit:

function() {
}

Eg:

var s = arr.reduce(/*The function
goes
here*/,0) // includes second argument

The 0 is not related to the function being passed, it's a second argument to reduce .

So the equivalent of your first block is:

var s = arr.reduce(() => {

}, 0) // includes second argument

Although of course, if you're using reduce , in both code blocks you're going to want some arguments:

var s = arr.reduce(function(result, current) {
    return /*...something combining `result` with `current`...*/;
}, 0);

So:

var s = arr.reduce((result, current) => {
    return /*...something combining `result` with `current`...*/;
}, 0);

Or:

var s = arr.reduce((result, current) => /*...something combining `result` with `current`...*/, 0)

You have to call the host function as usual, and can supply multiple arguments as usual. Just replace the function expression by the arrow function.

var s = arr.reduce(() => {
   …
}, 0);

Your second snippet did overwrite (assign to) arr.reduce , not invoke it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM