空值合并运算符(? ?)、可选链运算符(?.)

空值合并运算符(? ?)、可选链运算符(?.)

一、介绍及示例

空值合并运算符(? ?)
一个逻辑运算符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

注:与逻辑或运算符(||)不同,逻辑或运算符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,‘’ 或 0)时。

const foo = null ?? 'default string';
console.log(foo); // "default string"

const baz = 0 ?? 42;
console.log(baz); // 0

const baz = 0 || 42;
console.log(baz); // 42

可选链运算符(?.)
允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 运算符的功能类似于 . 链式运算符,不同之处在于,在引用为空 (nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。

const adventurer = {
    
    
  name: 'Alice',
  cat: {
    
    
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName); //undefined
console.log(adventurer.someNonExistentMethod?.()); // undefined

console.log(adventurer.someNonExistentMethod.()); 
// Error: Unexpected token  .'('

二、安装

vue项目使用选择依赖,配置babel

1、npm安装

npm install  @babel/plugin-proposal-optional-chaining // 可选链运算符 ?.
npm install  @babel/plugin-proposal-nullish-coalescing-operator // 空值合并运算符 ??

2、配置babel.config.js

module.exports = {
    
    
  plugins: [
    '@babel/plugin-proposal-optional-chaining',  // 可选链运算符 ?.
    '@babel/plugin-proposal-nullish-coalescing-operator'  // 空值合并运算符 ??
  ]
}

猜你喜欢

转载自blog.csdn.net/xxxxxxxx00772299/article/details/126980182