zoukankan      html  css  js  c++  java
  • ES6系列_7之箭头函数和扩展

    1.默认值

    在ES6中给我们增加了默认值的操作相关代码如下:

    function add(a,b=1){
        return a+b;
    }
    console.log(add(1));

    可以看到现在只需要传递一个参数也是可以正常运行的。

    输出结果为:2。

    2.主动抛出错误

    ES6中我们直接用throw new Error( xxxx ),就可以抛出错误。

    function add(a,b=1){
        if(a == 0){
            throw new Error('This is error')
        }
         return a+b;
    }
    console.log(add(0));

    在控制台可看到异常为:

    3.函数中的严谨模式

    我们在ES5中就经常使用严谨模式来进行编程,但是必须写在代码最上边,相当于全局使用。在ES6中我们可以写在函数体中,相当于针对函数来使用。例如:

    function add(a,b=1){
        'use strict'
        if(a == 0){
            throw new Error('This is error');
        }
         return a+b;
    }
    console.log(add(1));

    上边的代码如果运行的话,你会发现浏览器控制台报错,这个错误的原因就是如果你使用了默认值,再使用严谨模式的话,就会有冲突,所以我们要取消默认值的操作,这时候你在运行就正常了。

    function add(a,b){
        'use strict'
        if(a == 0){
            throw new Error('This is error');
        }
         return a+b;
    }
    console.log(add(1,2));

    结果为3。

    4.获得需要传递的参数个数

     ES6为我们提供了得到参数的方法(xxx.length).我们用上边的代码看一下需要传递的参数个数。

    function add(a,b){
        'use strict'
        if(a == 0){
            throw new Error('This is error');
        }
         return a+b;
    }
    console.log(add.length);//2

    这时控制台打印出了2,但是如果我们去掉严谨模式,并给第二个参数加上默认值的话,如下:

    function add(a,b=1){
    
        if(a == 0){
            throw new Error('This is error');
        }
        return a+b;
    }
    console.log(add.length);//1

    这时控制台打印出了1。

    总结:它得到的是必须传入的参数。

    5.箭头函数

    在箭头函数中,方法体内如果是两句话,那就需要在方法体外边加上{}括号

    var add =(a,b=1) => {
        console.log('hello world')
        return a+b;
    };
    console.log(add(1));//2

    待续。。

  • 相关阅读:
    中位数相关
    带权并查集
    组合数相关、多重集组合数
    LIS最长上升子序列
    提高你css技能的css开发技巧
    如何让搜索引擎抓取AJAX内容?
    Javascript异步编程的4种方法
    前端自动化构建工具gulp
    前端自动化构建工具
    git使用
  • 原文地址:https://www.cnblogs.com/wfaceboss/p/10053764.html
Copyright © 2011-2022 走看看