小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
函数是所有编程语言的重要组成部分,在ES6出现前,JS的函数语法一直没有太大的变化,从而遗留了很多问题和的做法,导致实现一些基本的功能经常要编写很多代码。ES6大力度地更新了函数特性,在ES5的基础上进行了许多改进,使用JS编程可以更少出错,同时也更加灵活。本文通过几个小栗子,介绍ES6函数扩展。
// es6函数扩展
{
function test(x, y = 'world'){
console.log('默认值',x,y);
}
// 当y的值没有传时才会取默认值
test('hello'); // 默认值 hello world
test('hello','bill'); // 默认值 hello bill
}
{
let x='test';
function test2(x,y=x){
console.log('作用域',x,y);
}
test2('bill'); // 作用域 bill bill
由于作用域的原因,因此输出都是undefined,因为形参y取的默认值x是形参x,而不是 外边定义的let x = 'test'
test3(); // 作用域 undifined undifined
}
{
let x='test';
function test2(c,y=x){
console.log('作用域',x,y);
}
test('bill'); // 作用域 bill test
}
// 将输入的值都转换成数组
{
// arguments 是一个类数组对象。代表传给一个function的参数列表,
function test3(...arg){
for(let v of arg){
console.log(v);
}
}
test3(1,2,3,4,'a'); // [1,2,3,4,a]
}
{
// 可以利用扩展运算符...将数组转成一个离散的值
console.log(...[1,2,4]); // 1 2 4
console.log('a',...[1,2,4]); // a 1 2 4
}
{
// 箭头函数
// 函数名 函数参数 返回值
let arrow = v => v*2;
// 相当于以下函数
function arrow(v){
return v*2
}
// 如果只有函数体只有一行代码,可以省去return
let arrow2 = () => 5;
console.log('arrow',arrow(3)); // arrow 6
console.log(arrow2()); // 5
let arrow3 = (c) => {
let b = c*2
return b // return 这种情况下return不能省略
}
}
// 尾调用:尾调用( Tail Call )是函数式编程的一个重要概念,本身非常简单,一句 // 话就能说清楚,就是指某个函数的最后一步是调用另一个函数。
{
function tail(x){
console.log('tail',x);
}
function fx(x){
return tail(x)
}
fx(123) // tail 123
}