I have defined following function
const fn = (a) => (console.log(...a));
Function works perfect when I call it with parameters:
fn(['asd','fgh']) // prints 'asd fgh'
However, is there any way to call it with undefined?
fn() //Uncaught TypeError: undefined is not iterable(…)
Only solution I can think about is to check it in the start of the function with an
if (a === undefined) a = '';
Is there any way I can make "...a" returns ' ', for example?
You can use default parameters. You can set up what value each parameter will have, if no value was passed in function call.
let fun = (a=3) => console.log(a);
fun(4); //4
fun(); //3
An alternative is(if it has to be a oneliner):
fn = a => a!==undefined && typeof a[Symbol.iterator] === 'function'? console.info(...a) : console.info(''); fn(); // result '' fn(1); // result '' fn([1,2,3]); // result 1 2 3
If the iterator part isn't a problem:
fn = a => a!==undefined ? console.info(...a) : console.info(''); fn(); // result '' try { fn(1); } catch(e){ console.info("told you:" + e); }; // throws an error fn([1,2,3]); // result 1 2 3
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.