为什么JavaScript可选链操作符返回undefined而非保留null值?
这是我在《Why does the TypeScript compiler compile its optional chaining and null-coalescing operators with two checks?》问题末尾偶然提出的后续问题,正如TypeScript领域知名贡献者jcalz在评论中指出的,该问题值得单独提问讨论。
// 为什么JavaScript将 x?.y // 处理为 x === null || x === void 0 ? void 0 : x.y // 而非 x === null || x === void 0 ? x : x.y // ?
当x == null时,后者的实现会保留null值,但前者的实现始终返回undefined。
现代浏览器原生支持?.语法,我们可以通过以下代码测试该行为:
const test = () => { console.log('undefined?.x\t\t==>\t', undefined?.x); console.log('null?.x\t\t\t==>\t', null?.x); console.log('null?.x === null\t==>\t', null?.x === null); }; try { eval('null?.x'); test(); } catch { console.error('Your browser does not support optional chaining syntax.'); console.info('While optional chaining is supported by all modern browsers, this will not work in browsers that do not support the syntax.') console.warn('😮'); console.info('Shocking, I know.'); console.info('Compatibility chart: 可选链语法浏览器兼容表'); }
内容的提问来源于stack exchange,提问作者dx_over_dt
相关产品推荐
相关产品推荐

