案例:将arr分别赋值给a,b,c
基本方法:
const arr = ["孙悟空", "猪八戒", "沙和尚"]
let a,
b,
c
a = arr[0]
b = arr[1]
c = arr[2]
console.log(a,b,c)
使用对象解构:
推荐在结构赋值前面手动加分号,防止编译器解析出问题
const arr = ["孙悟空", "猪八戒", "沙和尚"]
let a,
b,
c
;[a, b, c] = arr // 解构赋值
console.log(a,b,c)
但是一般使用的时候是声明和赋值在一起的(声明同时结构),但是如果前面参数比后面数组多,会被赋值undefined
let [d, e, f, g] = ["唐僧", "白骨精", "蜘蛛精", "玉兔精"]
console.log(d, e, f, g)
;[d, e, f, g] = ["唐僧", "白骨精", "蜘蛛精"]
console.log(d, e, f, g)
在赋值的时候给定默认值,就可以防止其出现undefined,如果设置了默认值,同时在数组解构的时候可以覆盖掉这个值,那么最终这个值存的是数组中的对应元素
有值就赋值,没有值就用默认值
;[d, e, f=73, g=10] = ["唐僧", "白骨精", "蜘蛛精"]
console.log(d, e, f, g)
在上面的例子中,g开始有值,但是在结构后又变成undefined了,我们想要的效果是如果可以赋值就赋值,不能赋值就用原来的,这样就可以通过下面这样设置来达到效果
let [d, e, f, g] = ["唐僧", "白骨精", "蜘蛛精", "玉兔精"]
console.log(d, e, f, g)
;[d, e, f, g=g] = ["唐僧", "白骨精", "蜘蛛精"]
console.log(d, e, f, g)
解构数组时,可以使用…来设置获取多余的元素
let [n1, n2, ...n3] = [4, 5, 6, 7]
console.log(n1, n2, n3)
function fn() {
return ["二郎神", "猪八戒"]
}
let [name1, name2] = fn() // "二郎神", "猪八戒"
let a1 = 10
let a2 = 20
// 原来的做法
let temp = a1
a1 = a2
a2 = temp
// 解构赋值
;[a1, a2] = [a2, a1] // [20, 10]
交换数组中两个元素的位置
const arr2 = ["孙悟空", "猪八戒"]
;[arr2[0], arr2[1]] = [arr2[1], arr2[0]]
const arr3 = [["孙悟空", 18, "男"], ["猪八戒", 28, "男"]]
let [[name, age, gender], obj] = arr3
console.log(name, age, gender)
console.log(obj)
const obj = { name: "孙悟空", age: 18, gender: "男" }
let { name, age, gender } = obj // 声明变量同时解构对象
console.log( name, age, gender)
这个必须得在解构的时候用括号括起来,不然会将大括号解析为代码块,然后会报错
const obj = {name: "孙悟空", age: 18, gender: "男"}
let name, age, gender
;({name, age, gender} = obj)
console.log( name, age, gender)
const obj = { name: "孙悟空", age: 18, gender: "男" }
let { address } = obj
console.log(address)
const obj = { name: "孙悟空", age: 18, gender: "男" }
// 设置别名
let {name: a, age: b, gender: c} = obj
console.log(a, b, c)
const obj = { name: "孙悟空", age: 18, gender: "男" }
// 设置默认值
let {name: a, age: b, gender: c, address: d = "花果山"} = obj
console.log(a, b, c, d)