1.函数默认参数
2.函数参数默认已经定义,不能在使用let,const声明
3.箭头函数
1) (参数)=> return的值
2) (参数)=>{语句 return的值 }
注意:
1) this问题:this指向定义时所在的对象,而不是使用时所在的对象。
箭头函数里面没有自己的this,而是引用外层的this。
2) 箭头函数没有arguments,用 '...'
3) 箭头函数不能成为构造函数
4.扩展运算符(rest运算符)
1. 展开: [1,2,3,4] -> ...[1,2,3,4] -> 1,2,3,4
2. 收起: 1,2,3,4 -> ... 1,2,3,4 ->[1,2,3,4]
3. 剩余参数:必须放到最后
//1. 函数默认参数
function test({a=0,b=0}={}){
console.log(a,b);
}
test({a:10,b:20});//10 20
test({b:20});//0 20
test({});//0 0
test();//0 0
// 2.函数参数默认已经定义,不能在使用let,const声明
function test(a){
let a=123; //error:Identifier 'a' has already been declared
console.log(a);
}
test(1);
// ================箭头函数============================
// 1. (参数)=> return的值
let test=(a,b)=>a+b;
console.log(test(1,2));//3
// 2. (参数)=>{语句 return }
let test=(a=0,b=0)=>{
console.log(a+b);
return a+b;
}
test(3,4);//7
test();//0
// 3.this问题:定义时所在的对象,而不是使用时所在的对象。
var id = 21;
function foo() {
setTimeout(() => {
console.log('id:', this.id);//this 指向函数foo的this
}, 100);
}
foo.call({ id: 42 });//42
// 箭头函数里面没有自己的this,而是引用外层的this。
function foo() {
console.log(this);//{id: 1}
return () => {
return () => {
return () => {
console.log(this);//this:是函数foo最外层的this
console.log('id:', this.id);
};
};
};
}
var f = foo.call({id: 1});
var t1 = f.call({id: 2})()(); //1
var t2 = f().call({id: 3})(); //1
var t3 = f()().call({id: 4});//1
// 4.箭头函数没有arguments,用 '...'
let test=()=>{
console.log(arguments);//error:arguments is not defined
}
test(1,2,3);
let test1=(...a)=>{
console.log(a);// [1, 2, 3]
}
test1(1,2,3);
//5.箭头函数不能成为构造函数
let Test=()=>{
this.name='assd';
console.log(this.name);
}
let test=new Test();//Test is not a constructor
// ================扩展运算符(rest运算符)=====================
// 1.收起 1,2,3,4,5 -> ...a -> [1, 2, 3, 4, 5]
function test(...a){
console.log(a); //数组 [1, 2, 3, 4, 5]
}
test(1,2,3,4,5);
// 2.展开 ...[1,2,3] -> 1 2 3
function test1(a,b,c){
console.log(a,b,c); //1 2 3
}
test1(...[1,2,3]);
// 3.剩余运算符
function test2(a,b,...c){
console.log(a,b); //1 2
console.log(c); //[3, 4, 5]
}
test2(1,2,3,4,5);
//4.数组复制,不影响原数组
let arr=[1,2,3,4,5];
let arr1=[...arr];
console.log(arr==arr1);//false
let arr2=Array.from(arr);//从一个类似数组或可迭代对象中创建一个新的数组实例。
console.log(arr==arr2);//false
// 5.rest参数代替 arguments
function test(){
return Array.prototype.slice.call(arguments).sort();
}
console.log(test(4,2,1,3)); //[1,2,3,4]
let test2=(...a)=>{
console.log(a);// [4, 2, 1, 3]
return a.sort();
}
console.log(test2(4,2,1,3)); //[1,2,3,4]