簡體   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