解构赋值:
用于解开数据体并赋值给变量。方便我们取出想要的多个值。
下面我们来看看具体使用:
数组解构:
<script>
// 数组解构,一一对应
let [a,b,c,d,e,f]=[1,2,3,4,5,6]
console.log(a,b,c,d,e,f)
// 变量多值少
let [a1,b1,c1]=[1,2]
console.log(a1,b1,c1)
// 变量少值多
let [a2,b2]=[1,2,3,4,5]
console.log(a2,b2)
// 按需取值,将间隔使用逗号隔开
let [,a3,,b3,,c3]=[1,2,3,4,5,6]
console.log(a3,b3,c3)
// 取剩余值
let [a4,...b4]=[1,2,3,4]
console.log(a4,b4)
// 复杂情况,所有的情况都要遵循一一对应的原则
// 这里我想取出2,4,5,7和8(其中7和8是数组)
let [,a5,,b5,[c5,,...d5]]=[1,2,3,4,[5,6,7,8]]
console.log(a5,b5,c5,d5)
</script>
结果:
对象解构:
对象解构使用的是{}形式,不过在声明变量时,只能使用对象元素名来接收对象解构而出的值:
<script>
function Obj(name, age, address, phone, testArr = [1, 2, 3], testObj = {a: 1, b: 2, c: 3}) {
this.name = name
this.age = age
this.addr = address
this.phone = phone
this.testArr = testArr
this.testObj = testObj
}
let obj = new Obj('polaris', 18, 'JS.NJ', '13200000001')
console.log(obj)
//换成了大括号,变量名也需要使用对象属性名
let {name, age, addr, phone, testArr} = obj
console.log(name, age, addr, phone, testArr)
//当然我们也可以使用取名式
let {name: diyName} = obj
console.log(diyName)
//当我们想取出数组中的某个值,我们需要使用:作为中间符号
let {testArr:[testVal1,...arg1]}=obj
console.log(testVal1,arg1)
//当我们想取出对象中的某个值,我们依旧使用:作为中间符号,但是一定要分辨重命名符号:和中间符:之间的区别
//复杂解构
let {testArr:[testVal2,...arg2],testObj:{a:testVal3,...arg3}}=obj
console.log(testVal2,arg2,testVal3,arg3)
</script>
执行结果:
下面我们来看看结构的一些实际开发用处:
<script>
let obj2={
name:'polaris',
age:18,
address:'JS.NJ',
owned:{
hand:'phone',
head:'earPhone',
body:'shirt'
}
}
function getObjInfo({name,age,address,owned:{head:whatInHead},owned},) {
console.log(name,age,address,whatInHead)
console.log(owned)
}
getObjInfo(obj2)
</script>
运行结果: