參考網站:
彭彭課程-參數預設值 (Youtube會員)
函式參數預設值 - 基礎範例
原有方式
1 2 3 4 5 6 7 8
| function show(message){ if(typeof message==="undefined"){ message="預設值"; } alert(message); } show("Hello"); show();
|
ES6的作法
若未給定message資料,直接採用=後方指定的資料
1 2 3 4 5
| function show(message="預設值"){ alert(message); } show("Hello"); show();
|
也可使用箭頭函式:
1 2 3 4 5
| let show=(message="預設值")=>{ alert(message); }; show("Hello"); show();
|
範例一:
1 2 3 4 5
| function multiply(n1, n2=1){ return n1*n2; } multiply(3,4); multiply(5);
|
範例一 箭頭函式:
1 2 3
| let multiply=(n1,n2=1)=>(n1*n2); multiply(3,4); multiply(5);
|
範例二:後面的參數可使用前面的參數名稱
1 2 3 4 5 6
| function combine(first="Louie",last="Chen",name=first+" "+last){ alert(name); } combine("祥祥","陳"); combine("祥祥"); combine();
|
範例二:箭頭函數
1 2 3 4 5 6
| let combibe=(first="Louie",last="Chen",name=first+" "+last)=>{ alert(name); } combine("祥祥","陳"); //顯示祥祥 陳 combine("祥祥"); //顯示 祥祥 Chen combine(); //顯示Louie Chen
|