/*
es6允许按照一定模式从数组和对象中提取值,然后对变量进行赋值,这被称为解构。
*/
// 以前,为变量赋值只能直接指定值
// let a = 1
// let b = 2
// let c = 3
// 现在,es6允许写成这样
let [a, b, c] = [1, 2, 3]
// 上面的代码表示,可以从数组中提取值,按照对应位置对变量赋值
// 本质上,这种写法属于"模式匹配",只要等号两边的模式相同,左边的变量就会被赋予对应的值.
let [foo, [[bar], baz]] = [1, [[2], 3]]
console.log(foo)
console.log(bar)
console.log(baz)
let [ , , third] = ['foo', 'bar', 'baz']
console.log(third) //baz
let [x, , y] = [1, 2, 3]
console.log(x) //1
console.log(y) //3
let [head, ...tail] = [1, 2, 3, 4]
console.log(head) //1
console.log(tail) //[2, 3, 4]
let [xx, yy, ...zz] = ['xx']
console.log(xx) //xx
console.log(yy) //undefined
console.log(zz) //[]
// 解构不成功时,foo都会变为undefined
// let [m] = []
// console.log(m) //undefined
// let [n, m] = [1]
// console.log(m) //undefined
// 解构成功的不完全解构
let [e, f] = [1, 2, 3]
console.log(e) //1
console.log(f) //2
let [g, [h], k] = [1, [2, 3], 4]
console.log(g) //1
console.log(h) //2
console.log(k) //4
// 如果等号右边不是数组(或者严格来说不是可遍历的结构),将会报错
3.1、数组的解构赋值
最新推荐文章于 2024-06-11 17:38:25 发布