在 ES6 中使用扩展语法时使用默认参数?

Use default parameter when using the spread syntax in ES6?

我知道您可以在 es6 中定义函数时使用带有参数(剩余参数)的扩展 operator 语法,如下所示:

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

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

我的问题:

您可以将默认参数与传播语法一起使用吗?这似乎不起作用:

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

JavaScript 不支持剩余参数的默认值。

您可以拆分参数并将它们的值合并到函数体中:

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

logDefault(); // "nothing"
logDefault("a", "b", "c"); // a, b, c

不,当没有剩余参数时,rest 参数会被分配一个空数组;无法为其提供默认值。

你会想要使用

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