函数解构赋值

函数解构赋值

基础语法

let arr1 = [1, 2];
    function show(arr) {
      console.log(arr[0], arr[1]);
    }
    show(arr1);

 
    let arr1 = [1, 2];
    function show([x, y]) {
      console.log(x, y);
    }
    show(arr1);

函数参数 默认值

    //函数结构赋值 - 默认值

    var a = { a1: 10 };
    function move(a) {
      console.log(a.a1);
    }
    move(a);

函数解构扩展

//右边的{ }如果没在调用方法的时候没有传参数那么就以左边{ } 里面的值为准
    function move({ x = 0, y = 0 } = {}) {
      console.log(x, y);
    }

    move({ x: 3, y: 10 }); // 3 ,10
    move({ x: 3 });
    move({});//0,0
    move();//0,0  


    function move({ x, y } = { x: 0, y: 0 }) {
      console.log(x, y);
    }

    //以调用的参数为准 有参打印的就那个参数 
    move({ x: 3, y: 10 }); //3 10
    move({ x: 3 }); //3 undefined
    move({}); //undefined undefined
    move();//0,0  // 会默认调用  { x: 0, y: 0 }


    function show(x, y = "你好") {
      alert(x + y);
    }

    show('小明'); // 小明你好
    show('小明', "你好肥"); // 小明你好肥
    show('小明', "");  //空字符串 也算一个参数
    show('小明',);  //没有写页算一个参数
    show('小明', null);  //没有写页算一个参数  null 也算一个值

    function foo({ x, y = 5 }) {
      console.log(x, y);
    }
    foo({}) // undefined 5
    foo({ x: 1 }) // 1 5
    foo({ x: 1, y: 2 }) // 1 2
    foo() // TypeError: Cannot read property 'x' of undefined
    
  	//参数默认值的位置
    function foo(x = 1, y) { console.log(x, y); }
    //foo(); // [1, undefined]
    //foo(2); // [2, undefined])
    //foo(, 1); // 报错
    //foo(undefined, 1); // [1, 1]
    foo(null, 1);

    console.log((function (a, b, c = 1) { }).length);//如果有默认值的 不算长度

    console.log((function (a, b = 1, c) { }).length);//如果 默认值在中间 那后面的不算
    
    console.log((function (a = 1, b, c) { }).length);

局限性

    不报错
    function show1(x, x, y) {
      console.log("老大 身材好");
    }
    show1(1, 1, 2);

    //如果 报错 你的参数中存在默认值 那么 参数列表如果存在同名 就会报错
    function show(x, x, y = 5) {
      console.log("老大  身材好");
    }
    show(1, 1, 2);

作用域

   //作用域
    var x = 5;
    function f(x, y = x) { console.log(y); }
    f(10); // 10
    //rest 参数实现求和
    function add(...values) { //...会把调用函数的参数变成数组
      let sum = 0;
      for (var val of values) { sum += val; }
      console.log(sum);
    }
    add(1, 2, 3) // 6
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值