简体   繁体   中英

Is there a way to provide two sets of rest parameters in one function definition?

I am trying to use a function that takes in an undetermined number of elements and classes. The number of elements will always match the number of classes. I know I can use rest parameters to accept an unknown number of arguments, but is it even possible to do that for two sets?

This is what I am thinking ⬇️:

const toggleClass = (axn, ...elements, ...classname) => {
    elements[0].classList[axn](classname[0])
    elements[1].classList[axn](classname[1])
}

heroBtn.addEventListener('mouseenter', () => toggleClass('add', arrowEl, btnTextEl, 'arrow-hover', 'btn-text-hover'))
heroBtn.addEventListener('mouseleave', () => toggleClass('remove', arrowEl, btnTextEl, 'arrow-hover', 'btn-text-hover'))

No - if that were possible, it would be unclear to the interpreter which argument goes into which rest parameter. Eg with

fn = (...args1, ...args1) => {

and

fn('foo', 'bar', 'baz')

How could the interpreter decide which elements to put in which array?

You'll have to separate out the elements yourself.

For what you're doing, I'd prefer to pass arrays:

toggleClass(
  'add',
  [arrowEl, btnTextE1],
  ['arrow-hover', 'btn-text-hover']
);

Then iterate over them.

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