目录
解构赋值
1. 定义:
2. 解构赋值概括:
数组解构
es5:
1.es6,数组解构
2.解构支持嵌套,左右结构对应即可
3.部分解构
4.赋默认值,解构出来的变量是undefined,默认值才会生效
5. 注意事项:
对象解构
es5
1.es6,对象解构
2.解构支持嵌套,左右结构对应即可,把握好结构的力度
3.对解构的变量名重命名
4.部分解构
6.注意事项
解构赋值
1. 定义:
es6允许按照一定模式,从数组和对象中提取,对变量进行赋值,这被称为解构。
2. 解构赋值概括:
2.1.赋值符号左右两边的结构必须一致(要么都是数组,要么都是对象)
2.2.变量的声明和赋值必须在一句话内完成。
数组解构
let arr = [ "杜兰特",33,"NBA职业球员" ]
es5:
let lastname = arrr[0]
let age = arr[1]
let job = arr[2]
1.es6,数组解构
let [lastname,age,job ] = arr
console.log(lastname,age,job)
2.解构支持嵌套,左右结构对应即可
let arr = [ "杜兰特",[33],"NBA职业球员" ]
let [lastname, [age] ,job ] = arr
console.log(age)
3.部分解构
let arr = [ "杜兰特",33,"NBA职业球员","篮网" ]
部分解构,前面部分使用逗号表示跳过即可
let [,age,job] = arr
console.log(age,job)
... 接收剩余部分,这里面rest是个数组
let [lastname,...rest] = arr
console.log(lastname,rest)
4.赋默认值,解构出来的变量是undefined,默认值才会生效
let arr = ['杜兰特',33]
let [,,team] = arr
console.log(arr)
let [,,team = "雷霆"] = arr
console.log(team)
let arr = [ "杜兰特" ,33,"篮网"]
let [,,team = "雷霆"] = arr
console.log(team)
5. 注意事项:
let arr = ['杜兰特',33]
5.1 左右解构不一致 => undefined
let [lastname,age ] = arr
console.log(lastname,age)
5.2 声明和赋值不在一句话内完成 => 报错
let [ lastname,age ]
[ lastname,age ] = arr
对象解构
let obj = { lastname:"杜兰特",age:"33",job:"NBA职业球员" }
es5
let lastname = obj[ "lastname" ]
let age = obj.age
let job = obj.job
1.es6,对象解构
let { lastname,age,job } = { lastnaem:"杜兰特",age:33,job:"NBA职业球员" }
//let { age,job lastname } = { lastnaem:"杜兰特",age:33,job:"NBA职业球员" } //对象是无序的
// let { lastname:lastname,age:age,job:job} = { lastnaem:"杜兰特",age:33,job:"NBA职业球员" }
console.log( lastname,age,job )
2.解构支持嵌套,左右结构对应即可,把握好结构的力度
let obj = {
name:{ lastname:"杜兰特",nickname:["包工头","杜小帅"] },
age:33,job:"NBA职业球员" }
// 取出lastname,nickname,age,job的值
let { name:{lastname,nickname},age,job} = obj
console.log( lastname,nickname,age,job )
//对nickname数组再次进行解构
let { name:{lastname,nickname},age,job} = obj
let [name1,name2] = nickname
console.log(name1,name2)
3.对解构的变量名重命名
let obj = { lastname:"杜兰特",age:"33",job:"NBA职业球员" }
let { lastname:uesrname
console.log(username,age)
4.部分解构
let obj = { lastname:"杜兰特",age:"33",job:"NBA职业球员",team:"篮网" }
...接收剩余部分,这里的rest是一个对象
let { lastname,...rest } = obj
console.log(lastname,rest)
5.默认值,解构出来的变量值是undefined,默认值才会生效
let obj = { lastname:"杜兰特",age:"33" }
let { lastname,team} = obj
console.log(lastname,team)
let { lastname,team = "雷霆" } = obj
console.log( lastname,team )
let obj = { lastname:"杜兰特",age:"33",team:"篮网" }
let { team = "雷霆",no:num = 7 } = obj
console.log( team,num)
6.注意事项
let obj = { lastname:"杜兰特", age:33,team:"篮网"}
6.1左右结构不一致 => 报错
let [lastname,age] = obj
console.log(lastname,age)
6.2声明和赋值不在同一句话内完成 => 完成
let {lastname,age}
{lastname,age} = obj
7. 应用
7.1 代替 对象.属性名 的取值
7.2.函数参数的结构,简化 对象...属性名 的取值写法
function add (obj){ return obj.x+obj.y }
consle.log(add( { x:12,y:24 } ))
//简写
function add ({ x,y }){ return x+y }
consle.log(add( { x:12,y:24 } ))