本文實例講述了ES6知識點整理之函數數組參數的默認值及其解構應用。分享給大家供大家參考,具體如下:
在ES6中, 函數的參數也可以使用解構賦值和默認值的設置,下面我們來看下
在ES6之前設置函數默認值的寫法
function test(x,y) {
x = x || 12;
y = y || 22;
console.log(x,y);
}
test(); // 12 22
test(1,2) // 1 2
在ES6中給函數參數賦默認值
function test(x=12, y=22) {
console.log(x,y);
}
test(); // 12 22
test(3,4); // 3 4
ES6中函數數組參數的默認值
function test([x=2,y=1]) {
console.log(x, y);
}
test([]); // 2, 1
test([3,4]) // 3 4
test(); // 報錯: 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 90
test(undefined, 80); // 2 1 80
test('', 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 90
test(undefined, undefined); // 2 3 4 90
test(undefined, 8); // 2 3 4 8
test([5,[]],12); // 5 3 4 12
test([5,[2,6]],12); // 5 2 6 12
注意其中的陷阱:
function test([x,y]=[1,2]) {
console.log(x,y);
}
test(); // 1 2
test([]); // undefined undefined
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行結果。
更多關于JavaScript相關內容可查看本站專題:《javascript面向對象入門教程》、《JavaScript查找算法技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。