简体   繁体   English

箭头函数可以包含宿主函数的多个参数,例如reduce吗?

[英]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. 下面是一个reduce函数,一个不使用箭头函数,一个是。 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. 这里, Array#reduce的第二个参数可以正常传递。 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 . 0与传递的函数无关,它是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: 虽然当然,如果你使用reduce ,在两个代码块中你都会想要一些参数:

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. 您的第二个片段覆盖(分配给) arr.reduce ,而不是调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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