前言
我错误的使用了解构赋值,导致了一个 bug,所以这里记录一下。
问题
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 ''
原因
每个解构属性都可以有一个默认值。当属性不存在或值为 undefined 时,将使用默认值。如果属性的值为 null,则不使用它。
const [a = 1] = []; // a is 1
const { b = 2 } = { b: undefined }; // b is 2
const { c = 2 } = { c: null }; // c is null
解决
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);
后记
当然有个别特殊情况也要注意一下
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.
上一篇
iOS Safari 下 CSS 100vh 高度问题及解决方案
iOS Safari 浏览器存在一个已知问题:使用 CSS 中的 `100vh` 属性时,高度往往会比屏幕实际高度多出一小部分。本文讨论了这个问题的成因,并提供了解决方案,使用`@supports (-webkit-touch-callout: none) { height: -webkit-fill-available; }`来修正 iOS Safari 下 `100vh` 不准确的问题。
下一篇
Vue Data Resetting Techniques
This article explores different methods for resetting data in Vue.js applications, including resetting the entire data object or specific properties using `this.$data` and `this.$options.data()`. Learn how to efficiently restore your component's data to its initial state.