ES6-----学习系列七(函数扩展)

在函数扩展方向也新增了一些特性,感觉这些特性也很重要

  一、参数默认值(注意:默认值的后面不可以在添加没有默认值的参数)

{
  function test(x, y = 'world'){
    console.log('默认值',x,y);
  }
  test('hello');//hello world
  test('hello','kill');//hello kill
}
{
  let x='test';
  function test2(x,y=x){
    console.log('作用域',x,y);
  }
  test2('kill');//kill kill  这里涉及到作用域的问题   函数里面具有单独的作用域  只有没有x的时候 才会继承let所声明的x
}

  二、rest参数(...) 将一系列离散的值 转化成数组  同样rest后面不可以再有参数

{
  function test3(...arg){
    for(let v of arg){
      console.log('rest',v);
    }
  }
  test3(1,2,3,4,'a');
}

  三、扩展运算符(...)将一个数组 转化成一系列离散的值  

{
  console.log(...[1,2,4]);
  console.log('a',...[1,2,4]);
}

  四、箭头函数(挺重要的 ,要不某些新的代码看不懂啊!!!) 例如 a=>a*2  a为参数   a*2为返回值  =>当做函数的象征   当不传递参数时可以用()表示

{
  let arrow = v => v*2;
  let arrow2 = () => 5;
  console.log('arrow',arrow(3));//6
  console.log(arrow2());//5

}

  五、尾调用  一个函数嵌套另一个函数  可以考虑尾调用

{
  function tail(x){
    console.log('tail',x);
  }
  function fx(x){
    return tail(x)
  }
  fx(123)// tail 123
}
原文地址:https://www.cnblogs.com/diasa-fly/p/7007327.html