ES6知识点整理之函数数组参数的默认值及其解构应用示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

ES6知识点整理之函数数组参数的默认值及其解构应用示例

Johnny丶me   2020-05-16 我要评论

本文实例讲述了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.softyun.net/code/HtmlJsRun测试上述代码运行结果。

希望本文所述对大家JavaScript程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们