本文实例讲述了ES6箭头函数和扩展。分享给大家供大家参考,具体如下:1.默认值1.默认值在ES6中给我们增加了默认值的操作相关代码如下:
function add(a,b=1){

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

return a+b;
}
console.log(add(1));可以看到现在只需要传递一个参数也是可以正常运行的。输出结果为:2。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));
function add(a,b=1){

if(a == 0){

throw new Error('This is error')

}

return a+b;
}
console.log(add(0));在控制台可看到异常为:3.函数中的严谨模式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=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));
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.获得需要传递的参数个数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
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
function add(a,b=1){


if(a == 0){

throw new Error('This is error');

}

return a+b;
}
console.log(add.length);//1这时控制台打印出了1。总结:它得到的是必须传入的参数。5.箭头函数5.箭头函数在箭头函数中,方法体内如果是两句话,那就需要在方法体外边加上{}括号
var add =(a,b=1) => {

console.log('hello world')

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

console.log('hello world')

return a+b;
};
console.log(add(1));//2感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools./code/HtmlJsRun测试上述代码运行效果。在线HTML/CSS/JavaScript代码运行工具在线HTML/CSS/JavaScript代码运行工具http://tools./code/HtmlJsRun关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》javascript面向对象入门教程JavaScript错误与调试技巧总结JavaScript数据结构与算法技巧总结JavaScript遍历算法与技巧总结JavaScript数学运算用法总结希望本文所述对大家JavaScript程序设计有所帮助。