2016-10-18 78 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