解構賦值是javascript 語法,作用是將值從數組、或屬性從對象,提取到不同的變量中。
1. 數組解構
1.1 聲明變量並賦值:
let hi = ['hello', 'world'];
let [hello, world] = hi
console.log(hello) => hello
console.log(world) => world
1.2 設置解構默認值
let hi = 'hello world';
let [hello, world = 'hi'] = hi
console.log(hello) => hello world
console.log(world) => hi
1.3 使用擴展運算符解構
function f () {
return ['hello', 'world', 'my', 'name', 'is Lilei'];
}
let [hello, world, ...who] = f()
console.log(hello) => hello
console.log(world) => world
console.log(who) => ['my', 'name', 'is Lilei']
1.4 忽略某些返回值
function f () {
return ['hello', 'world', 'my', 'name', 'is Lilei'];
}
let [hello, world,, ...who] = f() // 兩個逗號之間的值被忽略了
console.log(hello) => hello
console.log(world) => world
console.log(who) => ['name', 'is Lilei']
2. 對象解構
2.1 基本解構
let obj = {
hello: 'hello',
world: 'world'
}
let {hello, world} = obj
console.log(hello) => hello
console.log(world) => world
2.2 屬性重命名
let obj = {
hello: 'hello',
world: 'world'
}
let {hello: one, world: two} = obj;
console.log(one) => 'hello'
console.log(two) => 'world'
2.3 默認值
let obj = {
hello: 'hello'
}
let {hello, world = 'world'} = obj
console.log(hello) => hello
console.log(world) => world
2.4 重命名與默認值同時存在
let obj = {
hello: 'hello'
}
let {hello: one, world:two = 'world'} = obj
console.log(one) => hello
console.log(two) => world
2.5 爲函數參數設置默認值
function f ({name='Tim', hi={hello: 'hello', world: 'world'}, age: 18} = {}) {
console.log(name + ':' + hi + ':' + age)
}
f({
name: 'Tom',
age: 20
})
2.6 對象展開運算符
let obj = {
hello: 'hello',
world: 'world',
name: 'Tim',
age: 18
}
let {hello, world, ...hi} = obj;
console.log(hello) => hello
console.log(world) => world
console.log(hi) => {name: 'Tim', age: 18}
補充說明:
for 、 for of 、 for each 可以用來遍歷數組進行解構賦值
for in 可以用來遍歷對象屬性進行解構賦值
重命名現象僅能使用於對象解構賦值,因爲數組不存在名稱