乐趣区

关于前端:JS-逻辑运算符

记录一下空值合并操作符 ??(Nullish coalescing operator) 及 可选链操作符 ?. (Optional chaining)

// 空值合并操作符 ?? (Nullish coalescing operator)
// 只有当左侧为 null 和 undefined 时,才会返回右侧的数
const foo001 = null ?? ‘default string’;
console.log(foo001);
// expected output: “default string”

const foo002 = undefined ?? ‘default string’;
console.log(foo002);
// expected output: “default string”

const foo003 = 0 ?? 42;
console.log(foo003);
// expected output: 0

/*
留神:

?? 运算符不能与 AND 或 OR 运算符共用 
(来自 MDN https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)

*/

// null || undefined ?? “foo”; // 抛出 SyntaxError
// true || undefined ?? “foo”; // 抛出 SyntaxError

// ↑ 下面两行的写法也会被 eslint 校验报错 '||' and '??' operations cannot be mixed without parentheses
// 然而,如果应用括号来显式表明运算优先级,是没有问题的:
(null || undefined) ?? “foo”; // 返回 “foo”

/*
此外:

与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值 (false) 时返回右侧操作数。比方为假值(例如,'' 或 0)时。见上面的例子。

*/
const foo004 = ” || ‘default string’;
console.log(foo004);
// expected output: “default string”

const foo005 = ” ?? ‘default string’;
console.log(foo005);
// expected output: “”

const foo006 = 0 || 42;
console.log(foo006);
// expected output: 42

const foo007 = 0 ?? 42;
console.log(foo007);
// expected output: 0

// 可选链操作符 ?. (Optional chaining)
// 可选链操作符 ?. 容许读取位于连贯对象链深处的属性的值,而不用明确验证链中的每个援用是否无效。
// “?.” 操作符的性能相似于 “.” 链式操作符,不同之处在于,如果援用的属性不存在时 (null 或者 undefined),不会引发谬误,而是返回 undefined。
const adventurer = {
name: ‘Alice’,
cat: {

name: 'Dinah'

}
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

完结。
同步更新到本人的语雀
https://www.yuque.com/dirackeeko/blog/guggdutsegxzqrgl

退出移动版