[ES6]函数扩展

函数扩展
1、参数默认值
2、参数解构赋值
3、rest参数
4、…扩展运算符
5 、箭头函数


1.参数默认值

以前给参数默认值的做法

 function foo(param){
    let p = param || 'hello';
   console.log(p);
 }
 foo('hi');
  • 使用ES6语法做法
function foo(param = 'nihao'){
    console.log(param);
     }
 foo('hello');

2. 参数解构赋值

含多个参数,使用对象的形式

 function foo({uname='lisi',age=13}={}){
    console.log(uname,age);
 }
 foo({uname:'zhangsan',age:15});

3.rest参数(剩余参数)

把单个参数变成->数组


 function foo(a,b,...param){
    console.log(a);
    console.log(b);
    console.log(param);
 }
 foo(1,2,3,4,5);

1
2
[3, 4, 5]

4.扩展运算符 …

把数组拆散->变成单个参数

function foo(a,b,c,d,e,f,g){
    console.log(a + b + c + d + e + f + g);
}
// 传统调用方式
foo(1,2,3,4,5);

let arr = [1,2,3,4,5,6,7];
// 以前方式
foo.apply(null,arr);

//使用扩展运算符
foo(...arr);
// 合并数组
let arr1 = [1,2,3];
let arr2 = [4,5,6];
let arr3 = [...arr1,...arr2];
console.log(arr3);

猜你喜欢

转载自blog.csdn.net/weixin_43843847/article/details/89599079