arrow functions: destructuring arguments and grabbing them as a whole at the same time

天涯浪子 提交于 2019-12-10 10:38:12

问题


Can we do both destructuring: ({a, b}) => ( a + b ) and grab the arguments: (...args) => ( f({...args}) ), at the same time for arrow functions in ES6.

Looking for something like (...args = {a, b}) => ( a + b + f({...args}) ).

My curent solution is to do something like:

({a, b}) => {
  const {...args} = {a, b}
  return a + b + f({...args})
}

But it is redundant or (thanks to nnnnnn & Dmitry)

(args) => {
  const {a, b} = args
  return a + b + f({...args})
}

which is less redundant and definitely better but still not entirely satisfactory.


回答1:


You can use default parameters and object rest at target of destructuring assignment for first parameter, where a single object is expected, and optionally define subsequent parameters by destructuring previously defined object parameter

const fn = ({...args} = {}, {a, b} = args) => console.log(a, b, args);



回答2:


If you mean that f also accepts named parameters, so why not just use:

(params) => {
  const { a, b } = params
  return a + b + f(params)
}


来源:https://stackoverflow.com/questions/47117312/arrow-functions-destructuring-arguments-and-grabbing-them-as-a-whole-at-the-sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!