0%

200219-參數的預設值

參考網站:

彭彭課程-參數預設值 (Youtube會員)
函式參數預設值 - 基礎範例

原有方式

1
2
3
4
5
6
7
8
function show(message){
if(typeof message==="undefined"){ //未給定message資料
message="預設值";
}
alert(message);
}
show("Hello"); //顯示Hello
show(); //顯示預設值

ES6的作法

若未給定message資料,直接採用=後方指定的資料

1
2
3
4
5
function show(message="預設值"){
alert(message);
}
show("Hello"); //顯示Hello
show(); //顯示預設值

也可使用箭頭函式:

1
2
3
4
5
let show=(message="預設值")=>{
alert(message);
};
show("Hello"); //顯示Hello
show(); //顯示預設值

範例一:

1
2
3
4
5
function multiply(n1, n2=1){
return n1*n2;
}
multiply(3,4); //回傳12
multiply(5); //回傳5

範例一 箭頭函式:

1
2
3
let multiply=(n1,n2=1)=>(n1*n2);  //註:箭頭函式後方不用加上return,使用小括號會直接回傳
multiply(3,4); //回傳12
multiply(5); //回傳5

範例二:後面的參數可使用前面的參數名稱

1
2
3
4
5
6
function combine(first="Louie",last="Chen",name=first+" "+last){
alert(name);
}
combine("祥祥","陳"); //顯示祥祥 陳
combine("祥祥"); //顯示 祥祥 Chen
combine(); //顯示Louie Chen

範例二:箭頭函數

1
2
3
4
5
6
let combibe=(first="Louie",last="Chen",name=first+" "+last)=>{
alert(name);
}
combine("祥祥","陳"); //顯示祥祥 陳
combine("祥祥"); //顯示 祥祥 Chen
combine(); //顯示Louie Chen