1. 程式人生 > >ECMAScript 6知識點總結 --- 函式

ECMAScript 6知識點總結 --- 函式

  • 函式預設引數
    let func = (x = 1, y = 2) => {
        console.log(x ,y)
    }
    func()
    // 1, 2
    
    let func2 = ({x=0, y=0}={}) => {
        console.log(x, y)
    }
    func2()
    // 0, 0
    func2({x:1, y:2})
    // 1, 2

     

  • 函式預設引數已經定義了,不能再次宣告
    let func = (x=1, y=2) => {
        let x = 2  // 錯誤
        console.log(x ,y)
    }
    func()
    // Uncaught SyntaxError: Identifier 'x' has already been declared
    
  • 與...結合使用
    let func = (...a) => {
        console.log(a)
    }
    func(1,2,3,4,5)
    // [1,2,3,4,5]
    
    
    let func = (a,b,c) => {
        console.log(a,b,c)
    }
    func(...[1,2,3])
    // 1,2,3
    
    
    // 剩餘運算子 必須在最後一個引數
    let func = (a,b,...c) => {
        console.log(a,b,c)
    }
    func(1,2,3,4,5)
    // 1,2,[3,4,5]