箭头函数
function foo(){
console.log('hello');
}
foo();//hello
let foo1=()=>console.log('hello');
foo1();//hello
带有参数以及返回值的箭头函数定义
function foo(num){
return num
};//hello
//let foo=参数=>返回值
let re=foo('zs');
console.log(re);//zs
定义多个参数甚至多条函数执行体的结构
let foo2=(a,b)=>{
let c=100;
console.log(a+b+c)
};
foo2(1,2);//103
箭头函数循环遍历数组中的数据
let arr=[123,456,789];
arr.forEach(function(ele,index){
console.log(ele,index);
});
arr.forEach((e,index)=>{
console.log(e,index)
});
//结果为:123 0 456 1 789 2
箭头函数使用时需要注意的是箭头函数中this取决于函数的定义,而不是调用
function fo(){
console.log(this);
}
fo();//返回的结果:nodejs环境所有成员
改变this
function ff(){
console.log(this);
}
ff.bind({username:'123'});
function tt(){
setTimeout(()=>{
console.log(this.num);
},200)}
tt.call({num:100});//100
注意: 箭头函数不可以new
箭头函数不可以使用arguments获取参数列表,可以使用rest参数代替
let fg=(a,b)=>{
console.log(a,b);
}
fg(123,456);
let f2=(e,f)=>{
console.log(arguments);
}
f2(123,456);
是返回一个对象的列表(获取不到实参列表),如果想要获取数据,rest剩余参数
let kk=(...param)=>{
console.log(param);
}
kk(1,1);//[ 1, 1 ]