2026年AI应用趋势与关键技术解析
2026/10/29 12:01:41
写 JS 时最常见的啰嗦代码,就是一层层判断某个值存不存在。其实三个运算符就能把这些判断压到一行。
以前:
constname=user&&user.profile&&user.profile.name;现在:
constname=user?.profile?.name;中间任何一环是 null 或 undefined,整个表达式直接返回 undefined,不会报错。函数也能这样调:callback?.(),回调不存在时直接跳过。
constcount=input||10;// input 是 0 也会被替换成 10constcount=input??10;// 只有 null / undefined 才换成 10,0 和 '' 原样保留做默认值时,?? 比 || 更精确,不会误杀 0 和空字符串。
if(config.timeout==null)config.timeout=3000;// 等价于config.timeout??=3000;functiongreet(user){constname=user?.profile?.name??'访客';return`你好,${name}`;}```## 两个小坑 - ?? 不能和 &&、|| 混写不加括号:`a??b||c`会直接报语法错误,要写成`(a??b)||c`。-?.遇到 nullish 会短路,后面的整个链都不执行。 三个运算符都是ES2020/ES2021的特性,现代浏览器和较新的 Node 版本都已支持,放心用。