郑州哪里做网站汉狮,连云港网站定制开发,潍坊seo招聘,网站建设教程l1、基本使用
空值合并运算符#xff08;??#xff09;英文名称为 Nullish coalescing operator#xff0c;是一个逻辑运算符。
特性#xff1a;当左侧的操作数为 null 或者 undefined 时#xff0c;返回其右侧操作数#xff0c;否则返回左侧操作数。
const foo nul…1、基本使用
空值合并运算符??英文名称为 Nullish coalescing operator是一个逻辑运算符。
特性当左侧的操作数为 null 或者 undefined 时返回其右侧操作数否则返回左侧操作数。
const foo null ?? default string;
console.log(foo);
// expected output: default stringconst baz 0 ?? 42;
console.log(baz);
// expected output: 02、与逻辑或运算符||区别
与逻辑或运算符||不同的是当左侧操作数为 0、空字段、布尔false 时空值合并运算符??均返回左侧操作数。
const num 0 ?? 1;
console.log(num) // 0const flag false ?? true;
console.log(flag) //falseconst str ?? string;
console.log(str) // 上述场景如果使用 ||可能会出现不符合预期的结果因为||是布尔逻辑运算符左侧操作数会被强制转换为布尔值任何假值0 NaN null undefined都不会被返回而空值合并运算符可以有效避免上述问题。
3、??短路逻辑
此外??与 OR 和 AND 逻辑运算符相似当左表达式不为 null 或 undefined 时直接返回左侧表达式不会对右表达式进行求值。
const fn1 () {console.log(fn1被调用了); return fn1;}
const fn2 () {console.log(fn2被调用了); return fn2;}
const fn3 () {console.log(fn3被调用了); return null;}console.log(fn1() ?? fn2());
//打印 fn1被调用了
// fn1
// 由于fn1 返回值不为null、undefinedfn2 未被调用console.log(fn3() ?? fn2());
//fn3被调用了
//fn2被调用了
//fn2
// 由于fn3 返回值为nullfn2 被调用4、不能直接与逻辑 、||使用
要注意的是由于空值合并运算符??和其他逻辑运算符之间的运算优先级/运算顺序是未定义的不能直接与逻辑 、||使用否则会抛错通过括号明确运算优先级才能正确运行。
true null ?? default string // 抛出 SyntaxError
false || undefined ?? default string; // 抛出 SyntaxError(true null) ?? default string; // true
(false || undefined) ?? default string; //default string