简体   繁体   中英

Use default parameter when using the spread syntax in ES6?

I understand that you can use the spread operator syntax with parameters (Rest Parameters) when defining a function in es6 , like so:

function logEach(...things) {
  things.forEach(function(thing) {
    console.log(thing);
  });
}

logEach("a", "b", "c");
// "a" // "b" // "c" 

My question :

Can you use the default parameter along with the spread syntax ? This doesn't seem to work:

function logDefault(...things = 'nothing to Log'){
  things.forEach(function(thing) {
    console.log(thing);
  });
}
//Error: Unexpected token = 
// Note: Using Babel

JavaScript doesn't support a default for rest arguments.

You could split the arguments and merge their values in the function body:

 function logDefault(head = "nothing", ...tail) { [head, ...tail].forEach(function(thing) { console.log(thing); }); } logDefault(); // "nothing" logDefault("a", "b", "c"); // a, b, c 

No, a rest parameter gets assigned an empty array when there are no arguments left; there is no way to provide a default for it.

You'll want to use

function logEach(...things) {
  for (const thing of (things.length ? things : ['nothing to Log'])) {
    console.log(thing);
  }
}

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