zoukankan      html  css  js  c++  java
  • ES6新特性-函数的简写(箭头函数)

    通常函数的定义方法

    var fn = function(...){
        ......    
    }
    //例如:
    var add = function(a,b){
        return a+b;
    }
    
    //或者:
    function fn(...){
        ......
    }
    //例如:
    function add(a,b){
        return a+b;
    }

    简写方法速记

    将原函数的“function”关键字和函数名都删掉,并使用“=>”连接参数列表和函数体。

    function add(a,b){
        return a+b;
    }
    //简写为:
    (a,b)=>{//删掉了function和函数名
        return a+b;
    }
    
    var add = function(a,b){
        return a+b;
    }
    //简写为:
    var add = (a,b)=>{ //删掉了function
        return a+b;
    }

    附加规则

    1. 当函数参数只有一个时,括号可以省略;但是没有参数时,括号不可以省略。
    2. 函数体(中括号)中有且只有一行return语句时,中括号及return 关键字可以省略。

    新旧函数定义的对比

    无参数函数

    let fn = function(){
    return 'helloWorld';
    }
    
    //简写为:
    let fn = ()=>{//但是没有参数时,括号不可以省略
    return 'helloWorld';
    }
    //根据规则二,简写为:
    let fn = ()=>'helloWorld';

    一个参数的函数

    let fn = function(a){
        return a;
    }
    
    //简写为:
    let fn = (a)=>{
        return a;
    }
    //根据规则一,还可以简写为:
    let fn = a=>{
        return a;
    }
    //根据规则二,还可以简写为:
    let fn = a=>a;

    多个参数的函数

    let fn = function(a,b){
        return a+b;
    }
    //简写为:
    let fn = (a,b)=>{//多于一个参数,圆括号不可省略
        return a+b;
    }
    //根据规则二,还可以简写为:
    let fn = (a,b)=>a+b;

    函数体代码多于一行

    let fn = function(){
        console.log('hello');
        console.log('world');
        return 'helloWorld';
    }
    //简写为:
    let fn = ()=>{
        console.log('hello');
        console.log('world');
        return 'helloWorld';
    }

    函数返回json对象时

    let fn = function(){
        return {"a":5};
    }
    
    //简写为:
    //let fn = ()=>{"a":5};这是错误的
    //应简写为:
    let fn = ()=>({"a":5});//注意{}外的圆括号。

    实例

    //排序方法1
    let arr = [3,6,2,1];
    let arr2 = arr.sort(function(a,b){
        return a-b;
    });
    alert(arr2);
    
    //排序方法2
    let arr3 = [939,23,0,-1,94];
    let arr4 = arr3.sort((a,b)=>a-b);
    alert(arr4);
  • 相关阅读:
    xml和json笔记
    Ajax开发技术介绍与实战练习
    MATLAB学习(4)——min
    MATLAB学习(2)——zeros
    MATLAB学习(1)——ordfilt2
    vim的基本命令
    VS2015 闪退问题
    Error (10028): Can't resolve multiple constant drivers for net "mydata[14]" at sd_read.v(207)
    自动识别设备
    Internal Error: Sub-system: CUT, File: /quartus/db/cut/cut_post_syn_util.cpp, Line: 709 name_to_atom_map[iname] == 0
  • 原文地址:https://www.cnblogs.com/bing0709/p/10762116.html
Copyright © 2011-2022 走看看