JS解构赋默认值的注意事项

217 阅读1分钟

基础语法

解构对象的语法

const user = {
  id: 42,
  isVerified: true,
};

const { id, isVerified } = user;

console.log(id); // 42
console.log(isVerified); // true

多级解构赋默认值

多级属性如果可能没有值要用=来设置默认值,防止报错。

const user = {};

const {
  innerObj: { a, b = 2 } = {},
} = user;

console.log(a, b); // undefined 2

上述代码如果只有

const {
  innerObj: { a, b = 2 },
} = user;

会报错,中断程序运行。

解构null和undefined会报错

对象解构几乎等同于属性访问。这意味着,如果尝试解构基本类型的值,该值将被包装到相应的包装器对象中,并且在包装器对象上访问该属性。

const { a } = undefined;
// TypeError: Cannot destructure property 'a' of 'undefined' as it is undefined.
const { a } = null;
// TypeError: Cannot destructure property 'b' of 'null' as it is null.

**这里需要强调的是如果属性的值显式申明为null, 用默认值解构也会报错。 **

 const a = null;
 const { b = 2 } = a;
 
// TypeError: Cannot destructure property 'b' of 'null' as it is null.
 

别名

无效的 JavaScript 标识符作为属性名称,也就是常说的起别名。

const foo = { "fizz-buzz": true };
const { "fizz-buzz": fizzBuzz } = foo;

console.log(fizzBuzz); // true

const { a: aa = 10, b: bb = 5 } = { a: 3 };

console.log(aa); // 3
console.log(bb); // 5

属性默认值

每个解构属性都可以有一个默认值。当属性不存在或值为 undefined 时,将使用默认值。如果属性的值为 null,则不使用它。


const [a = 1] = []; // a is 1
const { b = 2 } = { b: undefined }; // b is 2
const { c = 2 } = { c: null }; // c is null