1.可选链操作符(?.)
const user = { address: { city: "beijing" } }; console.log(user.address?.city); // 输出 "beijing" console.log(user.unknown?.city); // 输出 undefined
当链式查找不到下一个属性时候,就会返回undefined
2.空值合并操作符(??)
当??的左侧值为 null 或 undefined的时候 就会取到右侧的 默认值
console.log(null ?? "default"); // 输出 "default" console.log(undefined ?? "default"); // 输出 "default" console.log("hello" ?? "default"); // 输出 "hello" console.log("" ?? "default"); // 输出 "" console.log(0 ?? "default"); // 输出 0 console.log(false ?? "default"); // 输出 false console.log(false || "default"); // 输出 default
注意??和||的区别??
:仅仅在 null
和 undefined
时返回 defaultvalue||
:不仅会在 null
和 undefined
时返回 defaultvalue,也会在 false
, 0
, ''
(空字符串) 等其他假值情况下返回默认值defaultvalue
3.优化判断
一般在判断if语句时候,经常会有类似的判断。 if(a.aa === undefined || a.aa === null || a.aa === ''){ }
是的,可以通过使用更简洁和可读性更高的方式来优化这种判断。以下是几种常见的优化方法:
3.1 使用 == 进行宽松比较
使用宽松相等运算符 ==
可以同时检查 undefined
和 null
:
if (a.aa == null || a.aa === '') { // 处理逻辑 }
3.2 使用逻辑非运算符 !
可以利用逻辑非运算符 !
来检查 falsy 值(如 undefined
、null
、''
、0
、nan
和 false
):
if (!a.aa) { // 处理逻辑 }
不过要注意,这种方式会将所有 falsy 值都视为 true
,如果你需要排除 0
或 false
,则不适用。
3.3 使用可选链和空值合并运算符
结合可选链操作符和空值合并运算符,可以更加简洁:
if (a.aa?.trim() === '') { // 处理逻辑 }
3.4 使用自定义函数
如果这种检查在多个地方使用,可以考虑封装成一个函数:
function isempty(value) { return value == null || value === ''; } if (isempty(a.aa)) { // 处理逻辑 }
总结
选择哪种方式取决于具体的需求和上下文。使用 !
运算符是最简洁的,但需要确保不会误判其他 falsy 值。如果需要更严格的检查,使用 ==
或自定义函数可能更合适。
到此这篇关于javascript 中处理 null和 undefined情况分析的文章就介绍到这了,更多相关js处理null和underfined内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论