0%

JS 解构赋值

前言

我错误的使用了解构赋值,导致了一个 bug,所以这里记录一下。

问题

1
2
3
4
5
6
7
8
9
10
const obj = {
a: null,
b: undefined,
c: 1,
d: ""
};

const { a = 1, b = 2, c = 3, d = 4 } = obj;

console.log(a, b, c, d); // 你猜猜会输出什么?

答案是 null 2 1 ''

原因

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#默认值

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

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

解决

1
2
3
4
5
6
7
8
9
10
11
const obj = {
a: null,
b: undefined,
c: 1,
d: ""
};

const { a, b, c, d } = obj;

// 可以用这个方法赋值初始值
console.log(a || 1, b || 2, c || 3, d || 4);

后记

当然有个别特殊情况也要注意一下

1
2
3
const { b = console.log("hey") } = { b: 2 };
// Does not log anything, because `b` is defined and there's no need
// to evaluate the default value.