对象解构时指定默认值

待解构字段为原始值

正常情况下,

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

解构时指定别名

你甚至可以在解构字段的同时为其重命名,

const obj = {
  a: 1,
  b: undefined
}

const { a, b: c = 2 } = obj;
console.log(a, c) // 1 2

上述过程其实为:

  • 创建变量 c
  • 获取 obj.b 并赋值给 c
  • 如果 obj.bundefined,则将指定的默认值 2 赋值给 c

上面的过程等同于:

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.

undefined & null

上面讨论的默认值仅在被解构字段的值为 undefined 时生效。拿被解构字段为原始为例,下面两种情况默认值都会生效:

  • 被解构字段缺失
const obj = {
  a: 1,
};

const { a, b = 2 } = obj;
console.log(a, b); // 1 2
  • 被解构字段显式地拥有 undefined
const obj = {
  a: 1
  b: undefined
}

const { a, b = 2 } = obj;
console.log(a, b) // 1 2

但如果被解构字段的值为非 undefined 时,比如 null,此时默认值并不生效,因为字段拥有 null 本身就是一种合法的值,所以再对其指定默认值便毫无意义。

于是,如下情况默认值不会生效:

const obj = {
  a: 1
  b: null
}

const { a, b = 2 } = obj;
console.log(a, b) // 1 null

这一规则在被解构字段为对象时同样适用。