用?.和??可安全读取localStorage嵌套属性并设默认值,避免层层判断、try/catch及临时变量,将传统8–10行逻辑压缩至2行。
直接用 ?. 和 ?? 替代层层判断和冗余默认值逻辑,就能大幅压缩读取 localstorage 对象的代码量。关键不是“少写几行”,而是去掉所有为防报错而写的防御性检查——这些检查过去常占一半以上体积。
安全读取嵌套属性,一步到位
localStorage 存的是字符串,通常要先 JSON.parse,再访问深层字段。传统写法需反复校验中间层:
- const data = localStorage.getItem('user');
const user = data ? JSON.parse(data) : {};
const city = user && user.profile && user.profile.address && user.profile.address.city || '未知';
换成可选链后,三步合一:
- const city = JSON.parse(localStorage.getItem('user') || '{}')?.profile?.address?.city ?? '未知';
?. 自动跳过 null/undefined 层级,不抛错;?? 只在最终结果为 null 或 undefined 时才用默认值,不会把 0、false、空字符串误判为“缺失”。
避免 JSON 解析失败导致整个流程中断
localStorage 里可能存了无效 JSON(比如手动编辑、旧版本残留),直接 parse 会报错。传统方案得加 try/catch,又增代码量。
- function safeParse(str) {
try { return JSON.parse(str); }
catch { return {}; }
} - const user = safeParse(localStorage.getItem('user'));
const email = user?.contact?.email || '';
更轻量的做法是结合空值合并与短路表达式:
将一个或多个视频上传至YouTube。当用户想“上传到YouTube”“发YouTube”“批量上传”“upload to YouTube”“post videos to YouTube”或发布到YouTube时使用此技能。
- const user = JSON.parse(localStorage.getItem('user') ?? '{}');
const email = user?.contact?.email ?? '';
这里 ?? '{}' 确保 getItem 返回 null/undefined 时也有合法字符串可 parse;后续 ?. + ?? 继续兜底,全程无 if、无 try、无临时变量。
设置默认结构,省掉初始化逻辑
很多场景下,我们希望“如果 localStorage 没有该键,就用一个完整默认对象”。过去要写:
- let config = localStorage.getItem('config');
if (!config) {
config = JSON.stringify({ theme: 'light', lang: 'zh', notifications: true });
localStorage.setItem('config', config);
}
const parsed = JSON.parse(config);
const lang = parsed.lang || 'zh';
现在可以一行声明并确保结构完整:
- const config = { theme: 'light', lang: 'zh', notifications: true, ...JSON.parse(localStorage.getItem('config') ?? '{}') };
const lang = config.lang ?? 'zh';
用展开语法融合默认值与存储值,?. 和 ?? 再负责字段级容错——原来 8–10 行的逻辑,压到 2 行内完成。

















