网络编程 
首页 > 网络编程 > 浏览文章

ES2020系列之空值合并运算符 '??'

(编辑:jimmy 日期: 2025/2/25 浏览:3 次 )

空值合并运算符 "htmlcode">

x = (a !== null && a !== undefined) "Anonymous"。
让我们使用 "htmlcode">
let firstName = null;
let lastName = null;
let nickName = "Supercoder";

// 显示第一个不是 null/undefined 的值
alert(firstName "Anonymous"); // Supercoder

与 || 比较

或运算符 || 可以与 "_blank" href="https://zh.javascript.info/logical-operators#or-finds-the-first-truthy-value" rel="external nofollow" >上一章 所讲的,我们可以用 || 替换上面示例中的 "htmlcode">

height = height "htmlcode">
let height = 0;

alert(height || 100); // 100
alert(height "color: #ff0000">优先级

"_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table" rel="external nofollow" >MDN table 中为 5。

因此,"htmlcode">

let height = null;
let width = null;

// 重要:使用括号
let area = (height "htmlcode">
// 可能不正确的
let area = height "htmlcode">
let x = 1 && 2 "htmlcode">
let x = (1 && 2) "color: #ff0000">总结

空值合并运算符 "htmlcode">

// 当 height 的值为 null 或 undefined 时,将 height 的值设置为 100
height = height ?? 100;

?? 运算符的优先级非常低,只略高于 ? 和 =。

如果没有明确添加括号,不能将其与 || 或 && 一起使用。

上一篇:vue页面跳转实现页面缓存操作
下一篇:解决vue单页面 回退页面 keeplive 缓存问题
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?