简体   繁体   中英

How to pass array using spread syntax into method in JavaScript

I am trying to pass an array into a method but having issues with quotes. Here is a case similar to what I am trying to achieve.

const remove = ['blue', 'round', 'tall']

function removeClass(param) {
    foo.classList.remove(param)
}  

removeClass(...remove)

The issue is that the result is foo.classList.remove('blue, round, tall') which won't work. I am trying to achieve this foo.classList.remove('blue', 'round', 'tall')

I have tried using remove.map(el => `'${el}'`).join(',') but then the result is foo.classList.remove("'blue', 'round', 'tall'") which also doesn't work.

Try using rest parameters:

const remove = ['blue', 'round', 'tall'];

function removeClass(...param) {
    foo.classList.remove(...param);
}  

removeClass(...remove);

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