2016-10-18 13 views
3

据我所知,您可以使用传播操作语法与参数(其余的力学参数)定义在ES6的功能,像这样的时候:在ES6中使用扩展语法时使用默认参数?

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 
+2

为什么会作出任何意义吗? 'things'将是一个包含其余参数的数组,其默认值为空数组。 –

+0

难道你不能只检查'things.length'来确定是否没有任何通过? –

+3

'...东西'被称为[休息参数](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/rest_parameters)(有人形容它为“聚会”)。语法与传播相同,但是相反。 – joews

回答

2

没有,当没有争论留下了其余参数被分配一个空数组;没有办法为它提供默认值。

你要使用

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

JavaScript不支持默认的休息参数。

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

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

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