ES6的箭头函数

ES6的箭头函数

  普通函数

let f2 = function(a) {
    return a;
}
f1(1); //1

 

  箭头函数

// 参数 => 函数体
let f1 = v => v;
f1(1); //1

 

这两种写法都是输出1,相当于把function给省略了,再在括号后面加上=>

let show1 = function () {
    console.log('show1');
}
let show2 = () => {
    console.log('show2');
}
show1(); // show1
show2(); // show2

 

  箭头函数带参数

let show1 = function (a, b) {
    console.log(a + b);
}
let show2 = (a, b) => {
    console.log(a + b);
}
show1(1, 2); // 3
show2(3, 4); // 7

 

  看个例子

// 普通写法
let arr = [12, 13, 20, 18, 22, 99]; arr.sort(function (a, b) { return a - b; }); console.log(arr); // [12, 13, 18, 20, 22, 99]
// 箭头函数写法
let arr = [12, 13, 20, 18, 22, 99];
arr.sort((a, b) => {
    return a - b;
});
            
console.log(arr); // [12, 13, 18, 20, 22, 99]

 

箭头函数要点:只有一个参数,() 可以省略,只有一个return {} 可以省

let show = function(a) {
    return a;
}
console.log(show(1)); // 1
            
let show2 = a => a;
console.log(show2(8)); // 8

 

  看个例子,函数体代码只有一个return(只有return 这一句代码),可以这样写

let arr = [12, 13, 20, 18, 22, 99];
arr.sort((a, b) => a - b);
console.log(arr); //  [12, 13, 18, 20, 22, 99]

 

posted @ 2019-10-20 19:22  花先生。  阅读(236)  评论(0编辑  收藏  举报