[英]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: 我知道在es6中定义函数时可以使用带有参数的扩展
运算符语法(Rest Parameters),如下所示:
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. JavaScript不支持rest参数的默认值。
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; 不,当没有参数时,rest参数被赋予一个空数组; 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.