解构赋值

在这里插入图片描述

解构赋值用法详解

数组解构

简单的解构数组

{
  let a,b,rest;
  [a,b]=[1,2];
  console.log(a,b);
}//1,2

剩余运算符的应用

{
  let a,b,rest;
  [a,b,...rest]=[1,2,3,4,5]
  console.log(a,b,rest);
}//1,2,[3,4,5]

如果配对不完全 可以设置默认值

{
  let a, b, c, rest;
  [a, b, c = 3] = [1, 2];
  console.log(a, b, c); 
}//1,2,3 如果没有给c赋值 则为undefined

应用场景 交换数值(比普通的要用中间变量简便的多)

{
  let a = 1;
  let b = 2;
  [a, b] = [b, a];
  console.log(a, b);
} //2 1

函数解构

将函数返回值赋给变量

{
  function f() {
    return [1, 2];
  }
  let a, b;
  [a, b] = f();
  console.log(a, b);
} // 1 2

选择性接收变量

{
  function f(){
    return [1,2,3,4,5]
  }
  let a,b,c;
  [a,,,b]=f();
  console.log(a,b);
}//1 4

数组长度未知时 返回第一个数值 剩余结构为数组

  function f(){
    return [1,2,3,4,5]
  }
  let a,b,c;
  [a,,...b]=f();
  console.log(a,b);
}//1,[3,4,5]

对象解构

简单对象解构

{
  let a,b;
  ({a,b}={a:1,b:2})
  console.log(a,b);
}//1 2
//另一种写法
{
  let p={a:1,b:2};
  let {a,b}=p;
  console.log(a,b);
}// 1 2

设置默认值

{
let {a=10,b=5}={a=3}
console.log(a,b)
}//3 5

模仿json文件解构

{
  let metaData={
    title:'abc',
    test:[{
      title:'test',
      desc:'description'
    }]
  }
let {title:estitle,test[{title:cdtitle}]}=metaData;
  console.log(esTitle,cnTitle);
}//abc test

字符串解构

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o

数值与布尔类型解构

let { toString: s } = 123;
console.log(s === Number.prototype.toString); // true
//1.先将123转为对象 new Number(123)
//2.Nummber对象有toString方法,解构成功
let { toString: x } = true;
console.log(x === Boolean.prototype.toString);// true
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值