ES6标准新增了一种新的函数:Arrow Function(箭头函数)。
常规函数定义:
function() {}
箭头函数,在定义函数时,移除了function
, return
和{}。
无参数案例:
const queue = ['Dave', 'Sarah', 'Sharon'];
const nextCustomer = () => queue[0];
console.log(nextCustomer()); // 'Dave'
有参数案例:
var a = [
"We're up all night 'til the sun",
"We're up all night to get some",
"We're up all night for good fun",
"We're up all night to get lucky"
];
// These two assignments are equivalent:
// Old-school:
var a2 = a.map(function(s){ return s.length });
// ECMAscript 6 using arrow functions
var a3 = a.map( s => s.length );
// both a2 and a3 will be equal to [31, 30, 31, 31]