您的位置:首页 > 其它

ES6系列_7之箭头函数和扩展

2018-12-02 15:51 260 查看

 

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

待续。。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: