before:
function foo(param){
let p = param || 'hello';
console.log(p);
}
foo('hi');
now:
function foo(param = 'nihao'){
console.log(param);
}
foo('hello kitty');
function foo(uname='lisi',age=12){
console.log(uname,age);
}
foo('zhangsan',13);
function foo({uname='lisi',age=13}={}){
console.log(uname,age);
}
foo({uname:'zhangsan',age:15});
function foo(a,b,...param){
console.log(a);
console.log(b);
console.log(param);
}
foo(1,2,3,4,5);
before:
function foo(a,b,c,d,e,f,g){
console.log(a + b + c + d + e + f + g);
}
let arr = [1,2,3,4,5,6,7];
foo.apply(null,arr);
now:
function foo(a,b,c,d,e,f,g){
console.log(a + b + c + d + e + f + g);
}
let arr = [1,2,3,4,5,6,7];
foo(...arr);
应用(合并数组):
// 合并数组
let arr1 = [1,2,3];
let arr2 = [4,5,6];
let arr3 = [...arr1,...arr2];//扩展运算符相当于把数组拆开了
console.log(arr3);
基本使用:
before:
function foo(){
console.log('hello');
}
foo();
now:
let foo = () => console.log('hello');
foo();
before:
function foo(v){
return v;
}
let ret = foo(111);
console.log(ret);
now:
function foo(v){
return v;
}
let foo = v => v;
let foo = (a,b) => {let c = 1; console.log(a + b + c);}
foo(1,2);
let arr = [123,456,789];
arr.forEach(function(element,index){
console.log(element,index);
});
arr.forEach((element,index)=>{
console.log(element,index);
});
注意事项:
1、箭头函数中this取决于函数的定义,而不是调用
function foo(){
// 使用call调用foo时,这里的this其实就是call的第一个参数
// console.log(this);
setTimeout(()=>{
console.log(this.num);
},100);
setTimeout(function(){
console.log(this.num);
},200);
}
foo.call({num:1});
2、箭头函数不可以new,不可以作为构造函数
let foo = () => { this.num = 123;};
new foo();
3、箭头函数不可以使用arguments获取参数列表,可以使用rest参数代替
let foo = function(a,b){
console.log(a,b);
console.log(arguments);//这种方式获取不到实参列表
}
foo(123,456);
let foo = (a,b) => {
console.log(a,b);
console.log(arguments);//这种方式获取不到实参列表
}
foo(123,456);
通过rest参数:
let foo = (...param) => {
console.log(param);
}
foo(123,456 );