待解构字段为原始值正常情况下, const obj = {a: 1,b: 2,};const { a, b } = obj;console.log(a, b); // 1 2 当被解构字段缺失时, const obj = {a: 1,};const { a, b } = obj;console.log(a, b); // 1 undefined 此时可在解构时使用 = 指定默认值: const obj = {a: 1,};const { a, b = 2 } = obj;console.log(a, b); // 1 2 解构时指定别名你甚至可以在解构字段的同时为其重命名, ad0const obj = {a: 1,b: undefined}const { a, b: c = 2 } = obj;console.log(a, c) // 1 2 上述过程其实为:
上面的过程等同于: const c = obj.b || 2 待解构字段为对象考察如下的对象: const obj = {innerObj: {a: 1,b: 2}} 正常情况下可通过如下的形式解构以得到内层的字段: const obj = {innerObj: {a: 1,b: 2,},};const {innerObj: { a, b = 2 },} = obj;console.log(a, b); // 1 2 但如果里面嵌套的对象缺失时,上面的解构会报错: const obj = {};const {innerObj: { a, b = 2 },} = obj;console.log(a, b); // ? error: Uncaught TypeError: Cannot read property \'a\' of undefined 此时需要在解构时对内层对象也指定默认值,形式如下: const obj = {};const {innerObj: { a, b = 2 } = {},} = obj;console.log(a, b); // undefined 2 解构字段包含在多层嵌套内当被解构字段包含在多层嵌套内时,甚至可以通过上面的方式为每一层都指定默认值: const obj = {}const { foo: { bar: { a, b = 2 } = {} } = {} } = obj;console.log(a, b) // undefined 2 对象解构时需要注意,当其为 null 时,上述默认值并不生效,仍会报错。具体见下方讨论。 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.
|
The text was updated successfully, but these errors were encountered: |
JavaScript 中对象解构时指定默认值
未经允许不得转载:爱站程序员基地 » JavaScript 中对象解构时指定默认值