JS中对象解构时(嵌套子对象)指定默认值

JS中对象解构时(嵌套子对象)指定默认值

待解构字段为原始值

正常情况下:

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

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

补充:函数参数-对象的解构赋值默认值

可参考另一篇文章:js函数参数的默认值,参数为对象

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值