- 箭头函数如何使用
箭头函数使用
- 正常函数写法.
function show()
{
alert('hello');
}
- 箭头函数写法.
() => {
alert('hello');
}
- 箭头函数传参
(text) => {
alert(text);
}
- 如果只有一个参数,()可以省略掉.
text => {
alert(text);
}
- 如果只有一个return,花括号可以省略.
原始写法:
let arr = [1, 4, 7, 2, 5, 8];
arr.sort(function (s1, s2) {
return s1 - s2;
}
);
箭头函数写法:
let arr = [1, 4, 7, 2, 5, 8];
arr.sort((s1, s2) => s1 - s2);
只需要记住两句话
- 如果只有一个参数, () 可以省略.
- 如果只有一个return, {} 可以省略.
- 箭头函数可以用也可以不用,它只是function的一个简写.