94-解构赋值

102 阅读2分钟

解构赋值

  • 概念:Es6的新特性,将数组、字符串、变量以指定格式展开,赋值给新变量,简化语法。

操作数组

  • 格式:let [变量名1,变量名2...] = obj
  • 作用:将数组中的数据罗列出,赋值给对应的变量
let arr = [22,33,44]
1.对数组进行解构
let [a,b,c] = arr  //a:22  b:33 c:44
2.部分解构
let [a,b] = arr  //a:22  b:33 根据下标进行对应
3.跳位置解构
let [,b] = arr  //b:33
4.取到不存在的数据
let [a,b,c,d] = arr  //a:22  b:33 c:44 d:undefined
5.设置默认值
let [a,b,c,d=100] = arr  //a:22  b:33 c:44 d:100
6.部分存储在数组中
let [a,...newArr] = arr //a:22 newArr:[33,44]

字符串

  • 格式:let [变量名1,变量名2...] = obj
  • 作用:将字符串中的字符罗列出,赋值给对应的变量
let str = "1234"
1.对数组进行解构
let [a,b,c] = str  //a:”1“  b:”2“ c:”3"
2.部分解构
let [a,b] = str  //a:"1"  b:"2" 根据下标进行对应
3.跳位置解构
let [,b] = str  //b:"2"
4.取到不存在的数据
let [a,b,c,d,f] = str  //f:undefined
5.设置默认值
let [a,b,c,d,f=100] = str  // f:100
6.部分存储在数组中
let [a,...newArr] = strr //a:1 newArr:["2","3","4"]

对象

  • 格式:let {变量名1,变量名2...} = obj
  • 作用:将对象中的属性一一罗列出,将属性值赋值给同名变量
let obj = {id:1,name:"小王",gender:"男"}
1.解构对象 属性名进行对应 解构值为对应的属性值
let {name,gender} = obj //"小王" ”男“
2.设置默认值
let {height="160"} = obj //height:"160"
3.设置新的变量名——属性名:变量名
let {name:studentname} = obj //studentname:"小王"
4.取出部份数据 剩余数据放入新的对象中
let {name,...newObj} = obj  //name:小王  newObj{id:1,gender:"男"}
5.函数 形参解构处理
function demo({id:a}){
    console.log(a);//a表示形参,传入数据为id对应属性值
}
demo(obj)