es6中函数默认参数、箭头函数、剩余参数-讲解

1.函数默认参数,调用时最后一个参数不传相应实参也可以执行

function show(a="哈哈",b="你好") {
    console.log(a,b);
}
show('啦啦',);//啦啦 你好
function show2({x,y=0}) {
    console.log(x,y)
}
show2({x:1});//1,0

2.函数的参数名默认已经定义了,不能再用let,const重复定义

function show3(a=18) {
    let a=100;
    console.log(a)
}
show3();//报错Identifier 'a' has already been declared

3.三个点... 扩展运算符、rest运算符,剩余运算符,可应用于展开数组 重置数组 排序

let arr=['apple','banana','orange'];
    console.log(...arr);//apple banana orange
//展开数组
function show4(...a) {
    console.log(a);
}
show4(1,2,3,4,5);//[1, 2, 3, 4, 5]
//重置数组
function show4(...arr1) {
    //let arr1=Array.prototype.slice.call(arguments);
    return arr1.sort();
}
console.log(show4(10,2,111,4,50));//按照首数字排序。非大小
//排序
function show5(a,b,c) {
      console.log(a,b,c);
}
show5(...[1,9,8]);//1 9 8
function show6(a,b,...c) {
      console.log(a,b);
      console.log(c)
}
show6(1,2,3,4,5);//1 2  //[3,4,5]
//接收剩余的参数为数组
let arr3=[1,2,3,4,5],
    arr4=[...arr3];
    //等同于
let arr5=Array.from(arr3);
console.log(arr3,arr4,arr5);
//复制数组
let str='a-b-c';
let arr6=Array.from(str);
console.log(arr6);//["a", "-", "b", "-", "c"];
//字符串拆成单个字符的数组

4.箭头函数

function show7() {
      return 1;
}
//等同于
let show8=()=>1;
console.log(show7(),show8()); //1 1
let show9=(d=8,f=12)=>{
     console.log(d,f);
     return d+f;
};
show9(5,12);
console.log(show9(5,12));//17
格式1:()=>return的东西,实用性不高
格式2:
()=>{
语句;
    return;
}
var id=10;//var 定义一个变量属于window
let json={
    id:1,
    show:function() {
        setTimeout(()=>{
            alert(this.id);//谁调用this,this就是谁的。即this为定义函数所在的对象,不是在运行时所在的对象。
        }//1而不是10
        ,2000);
        alert(this.id);
    }
};
json.show();

(1)当你用了箭头函数,this不属于当前函数,是属于当前定义的对象所在的范围。
(2)在箭头函数里面没有arguments,用...解决
(3)箭头函数不能当构造函数

let show10=(...args)=>{
    console.log(args);
};
show10(1,2,3,4,5);
let show11=()=>{
    this.name='abc';
};
let s=new show11();
alert(s.name);//报错
ajax(url,(res)=>{
    //当前函数没有this作用域
})

es5:this被谁调用this属于谁,箭头函数的this是定义函数所在的对象。

猜你喜欢

转载自blog.csdn.net/JackieDYH/article/details/116800529