繁体   English   中英

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

[英]Use default parameter when using the spread syntax in ES6?

我知道在es6中定义函数时可以使用带有参数的扩展运算符语法(Rest Parameters),如下所示:

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不支持rest参数的默认值。

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

 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);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM