最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
ES6箭头函数和扩展代码实例解析
时间:2020-05-23 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下ES6箭头函数和扩展代码实例解析,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
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
相关文章
- ES6 async与await如何使用 ES6 async与await基本使用方法 06-06
- ES6扩展运算符和rest运算符如何用 ES6扩展运算符和rest运算符用法代码示例 05-23
- ES6对象操作实例代码详解 05-23
- ES6使用Array.includes处理多重条件用法实例分析 03-02
- es6解构经验分享 08-31
- SpringBoot测试配置属性与web启动环境解析 10-24