美文网首页
(二)11.函数扩展19-08-08

(二)11.函数扩展19-08-08

作者: 你坤儿姐 | 来源:发表于2019-08-09 11:17 被阅读0次
WechatIMG74.png
  • 参数默认值
{
  function test(x,y = 'world') {
    console.log('默认值',x,y);
  }
  test('hello');
  test('hello','kill');

  //默认值的后面 不能再跟没有默认值的参数,
  /**
   * 默认值的后面 不能再跟没有默认值的参数,错误写法❌
  function test(x,y = 'world',c) {
    console.log('默认值',x,y);
  }
   */
  /**
   * 默认值的后面 不能再跟没有默认值的参数,正确写法✔️
   function test(x,y = 'world',c = 'fuck') {
    console.log('默认值',x,y);
  }
   */
}

打印结果:
默认值 hello world
默认值 hello kill

  • 作用域概念
{
  let x='test';
  //y这里x取的不是上面的x
  function test2(x,y=x) {
    console.log('作用域',x,y);
  }
  test2('kill');
  test2();
}

{
  let x='test';
  function test2(c,y=x) {
    console.log('作用域',c,y);
  }
  test2('kill');
}

打印结果:
作用域 kill kill
作用域 undefined undefined

作用域 kill test

  • rest
{
  //rest参数  rest参数就是把一系列参数转为一个数组, rest参数之后不能有其他的参数
  function test3(...arg) {
    for (let v of arg){
      console.log('rest',v);
    }
  }
  test3(1,2,3,4,'a');
}

打印结果:
rest 1
rest 2
rest 3
rest 4
rest a

  • 扩展运算符
{
  //扩展运算符  件数组离散成一系列参数
  console.log(...[1,2,4]);
  console.log('a',...[1,2,4]);
}

打印结果:
1 2 4
1 a 1 2 4

{
  //箭头函数 第一个v是参数(如果参数写一个空的括号) 然后用=>连接 后面的v*2是返回值
  let arrow = v => v*2;
  let arrow2 = () => 5;
  console.log('arrow',arrow(3));
  console.log('arrow2',arrow2());
}

打印结果:
arrow 6
arrow2 5

  • 尾调用
{
  //尾调用  用于提升性能
  function tail(x) {
    console.log('tail',x);
  }
  function fx(x) {
    return tail(x)
  }
  fx(123)
}

打印结果:
tail 123

相关文章

网友评论

      本文标题:(二)11.函数扩展19-08-08

      本文链接:https://www.haomeiwen.com/subject/kpqfjctx.html