JavaScript 中對(duì)象解構(gòu)時(shí)指定默認(rèn)值
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
作者 | 劉哇勇
來(lái)源 | urlify.cn/y2Yzu2
待解構(gòu)字段為原始值
正常情況下,
const obj = {
a: 1,
b: 2,
};
const { a, b } = obj;
console.log(a, b); // 1 2
當(dāng)被解構(gòu)字段缺失時(shí),
const obj = {
a: 1,
};
const { a, b } = obj;
console.log(a, b); // 1 undefined
此時(shí)可在解構(gòu)時(shí)使用 = 指定默認(rèn)值:
const obj = {
a: 1,
};
const { a, b = 2 } = obj;
console.log(a, b); // 1 2
解構(gòu)時(shí)指定別名
你甚至可以在解構(gòu)字段的同時(shí)為其重命名,
const obj = {
a: 1,
b: undefined
}
const { a, b: c = 2 } = obj;
console.log(a, c) // 1 2
上述過(guò)程其實(shí)為:
創(chuàng)建變量
c獲取
obj.b并賦值給c如果
obj.b為undefined,則將指定的默認(rèn)值2賦值給c
上面的過(guò)程等同于:
const c = obj.b || 2
待解構(gòu)字段為對(duì)象
考察如下的對(duì)象:
const obj = {
innerObj: {
a: 1,
b: 2
}
}
正常情況下可通過(guò)如下的形式解構(gòu)以得到內(nèi)層的字段:
const obj = {
innerObj: {
a: 1,
b: 2,
},
};
const {
innerObj: { a, b = 2 },
} = obj;
console.log(a, b); // 1 2
但如果里面嵌套的對(duì)象缺失時(shí),上面的解構(gòu)會(huì)報(bào)錯(cuò):
const obj = {};
const {
innerObj: { a, b = 2 },
} = obj;
console.log(a, b); // ?? error: Uncaught TypeError: Cannot read property 'a' of undefined
此時(shí)需要在解構(gòu)時(shí)對(duì)內(nèi)層對(duì)象也指定默認(rèn)值,形式如下:
const obj = {};
const {
innerObj: { a, b = 2 } = {},
} = obj;
console.log(a, b); // undefined 2
解構(gòu)字段包含在多層嵌套內(nèi)
當(dāng)被解構(gòu)字段包含在多層嵌套內(nèi)時(shí),甚至可以通過(guò)上面的方式為每一層都指定默認(rèn)值:
const obj = {}
const { foo: { bar: { a, b = 2 } = {} } = {} } = obj;
console.log(a, b) // undefined 2
對(duì)象解構(gòu)時(shí)需要注意,當(dāng)其為 null 時(shí),上述默認(rèn)值并不生效,仍會(huì)報(bào)錯(cuò)。具體見下方討論。
const obj = {
foo: {
bar: null
}
}
const { foo: { bar: { a, b = 2 } = {} } = {} } = obj;
console.log(a, b) // ?? error: Uncaught TypeError: Cannot destructure property 'a' of '{}' as it is null.
undefined & null
上面討論的默認(rèn)值僅在被解構(gòu)字段的值為 undefined 時(shí)生效。拿被解構(gòu)字段為原始為例,下面兩種情況默認(rèn)值都會(huì)生效:
被解構(gòu)字段缺失
const obj = {
a: 1,
};
const { a, b = 2 } = obj;
console.log(a, b); // 1 2
被解構(gòu)字段顯式地?fù)碛?nbsp;
undefined值
const obj = {
a: 1
b: undefined
}
const { a, b = 2 } = obj;
console.log(a, b) // 1 2
但如果被解構(gòu)字段的值為非 undefined 時(shí),比如 null,此時(shí)默認(rèn)值并不生效,因?yàn)樽侄螕碛?nbsp;null 本身就是一種合法的值,所以再對(duì)其指定默認(rèn)值便毫無(wú)意義。
于是,如下情況默認(rèn)值不會(huì)生效:
const obj = {
a: 1
b: null
}
const { a, b = 2 } = obj;
console.log(a, b) // 1 null
這一規(guī)則在被解構(gòu)字段為對(duì)象時(shí)同樣適用。

粉絲福利:Java從入門到入土學(xué)習(xí)路線圖
??????

??長(zhǎng)按上方微信二維碼 2 秒
感謝點(diǎn)贊支持下哈 
