1. 程式人生 > >ES6 函數的擴展

ES6 函數的擴展

img define fin ava code cti word 不用 operator

ES6 允許函數指定參數默認值,如果傳遞的參數布爾值為false,則不會為默認值

function fn(x,y){
  y = y || world
  console.log(x,y)  
}

fn("hello","china"), //hello china
fn("hello","") //hello
fn("hello") //hello world

//也可以直接設置默認值,寫在參數後面
function fn(x=0,y=0){
  console.log(x,y)
}

參數是默認聲明的,不用聲明 如果在函數體內重新聲明默認參數,則報錯

技術分享

參數默認值,不能重名

與解構賦值結合使用

function
fn({x,y=1}){ console.log(x,y) } 只有當參數是對象時,才會賦值成功 fn({}) //undefined 1 fn() //參數不是對象,報錯 fn({x:1,y:3}) //1 3

function foo({x, y = 5} = {}) {
  console.log(x, y);
}

foo() //undefined 5  沒有參數,默認是個空對象
 

ES6 函數的擴展