函数默认参数、箭头函数

函数可以给默认参数

    function show(a = '默认', b = '系统'){ //不传参数时显示的值
                console.log(a,b);
            }
            show('hello'); //  hello 系统

函数参数默认已经定义了,不能再用let,const声明了

      //以下程序报错
        function demo(a = 18){//函数里的参数默认已经定义
            let a = 10;//这里不能再重复定义
            console.log(a);
        }
        demo()

扩展运算符(三个点)

可以展开数组

   var arr = ['banana','apple','orange'];
     console.log(arr);//Array(3) ["banana", "apple", "orange"]
     console.log(...arr);//banana apple orange

运用于传参

  function demo(...a){
            console.log(a);//Array(5) [1, 2, 3, 4, 5]
        }
        demo(1,2,3,4,5);

将字符串转为数组

[...'hello']
// [ "h", "e", "l", "l", "o" ]

复制一个数组,新数组发生改变时不改变原数组的值

     var arr = [1,3,2,7,5];
     var arr2 = [...arr];
     arr.pop();
     arr2.push(10);
     console.log(arr);//Array(4) [1, 3, 2, 7]
     console.log(arr2);//Array(6) [1, 3, 2, 7, 5, 10]

直接引用时一个数组发生改变时,另一个数组也会发生改变

     var arr = [1,3,2,7,5];
     var arr2 = arr;
     arr.pop();
     arr2.push(10);
     console.log(arr);//Array(4) [1, 3, 2, 7, 10]
     console.log(arr2);//Array(6) [1, 3, 2, 7, 10]

箭头函数(=>)

格式
let 函数名 = () => {
函数体在这里插入代码片
}

注意点
1.this:箭头函数里,this指向定义函数时指向的对象,不再是运行时所在的对象

  var id = 10;
      let json = {
          id : 1,
          name : 'yang',
          say : function(){
              setTimeout(function(){//普通函数
                  alert(this.id);//10
              },1000)
          },
          show : function(){
              setTimeout(() => {//使用了箭头函数
                  alert(this.id);//1
              }, 2000);
          },
          
      }
      json.say();
      json.show();

2.arguments:箭头函数里没有arguments,用‘…’。

 let show=()=>{
        console.log(arguments);//报错 ReferenceError: arguments is not defined
    }
    show(1,5,7,3)
  let show=(...arguments)=>{
        console.log(arguments);//Array(4) [1, 5, 7, 3]
    }
    show(1,5,7,3)

3.箭头函数不能当构造函数

    let show=()=>{
       this.name = 'yang'
    }
    let s = new show();
    console.log(s.name);//报错 TypeError: show is not a constructor
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值