本文實例講述了ES6知識點整理之函數數組參數的默認值及其解構應用。分享給大家供大家參考,具體如下:
在ES6中, 函數的參數也可以使用解構賦值和默認值的設置,下面我們來看下
在ES6之前設置函數默認值的寫法
function test(x,y) { x = x || 12; y = y || 22; console.log(x,y);}test(); // 12 22test(1,2) // 1 2
在ES6中給函數參數賦默認值
function test(x=12, y=22) { console.log(x,y);}test(); // 12 22test(3,4); // 3 4
ES6中函數數組參數的默認值
function test([x=2,y=1]) { console.log(x, y);}test([]); // 2, 1test([3,4]) // 3 4test(); // 報錯: Uncaught TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
解決上述最后一個錯誤:使用默認數組來匹配沒有參數的情形
function test([x=2,y=1]=[]) { console.log(x, y);}test(); // 2 1
更多應用:
function test([x=2,y=1]=[], z=90) { console.log(x, y, z);}test(); // 2 1 90test(undefined, 80); // 2 1 80test('', 50); // 2 1 50 正常輸出// test(null, 80); // 報錯,不能填入null Uncaught TypeError: Cannot read property 'Symbol(Symbol.iterator)' of object// test(NaN, 60); // 報錯: Uncaught TypeError: undefined is not a function
注意上面函數參數可以接受undefined,但不能接受null和NaN
下面則是更復雜的應用
function test([x=2,[y=3,w=4]=[]]=[], z=90) { console.log(x, y, w, z);}test(); // 2 3 4 90test(undefined, undefined); // 2 3 4 90test(undefined, 8); // 2 3 4 8test([5,[]],12); // 5 3 4 12test([5,[2,6]],12); // 5 2 6 12
注意其中的陷阱:
function test([x,y]=[1,2]) { console.log(x,y);}test(); // 1 2test([]); // undefined undefined
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答