1、无参数函数
let fn = function(){ return 'helloWorld'; } //简写为: let fn = ()=>{//但是没有参数时,括号不可以省略 return 'helloWorld'; } //根据规则二,简写为: let fn = ()=>'helloWorld';
2、一个参数的函数
let fn = function(a){ return a; } //简写为: let fn = (a)=>{ return a; } //根据规则一,还可以简写为: let fn = a=>{ return a; } //根据规则二,还可以简写为: let fn = a=>a;
3、多个参数的函数
let fn = function(a,b){ return a+b; } //简写为: let fn = (a,b)=>{//多于一个参数,圆括号不可省略 return a+b; } //根据规则二,还可以简写为: let fn = (a,b)=>a+b;
4、函数体代码多于一行
let fn = function(){ console.log('hello'); console.log('world'); return 'helloWorld'; } //简写为: let fn = ()=>{ console.log('hello'); console.log('world'); return 'helloWorld'; }
5、函数返回json对象时
let fn = function(){ return {"a":5}; } //简写为: //let fn = ()=>{"a":5};这是错误的 //应简写为: let fn = ()=>({"a":5});//注意{}外的圆括号。