js 运算符

  /**
   *  ?? 非空运算符允许我们在忽略错误值(如 0 和 null)的同时指定默认值
   * **/
  let currMoney = 0
  let noAccount = null

  function moneyAmount(money) {
    return money ?? `账户未开通`
  }

  console.log(moneyAmount(currMoney)) // => 0
  console.log(moneyAmount(noAccount)) // => `账户未开通`

  /**
   *  ??=  空赋值运算符仅当值为 null 或 undefined 时,此赋值运算符才会赋值
   * **/
  let x = null
  let y = 5
  console.log(x ??= 5) // => 5
  // 结合上面使用
  console.log(x = (x ?? y)) // => 5

  /**
   *  ?. 链判断运算符允许开发人员读取深度嵌套在对象链中的属性值,而不必验证每个引用。当引用为空时,
   *  表达式停止计算并返回 undefined。
   * */
  let arr = [1, 2, 3]
  console.log(arr?.length) // 3  等价于 arr && arr.length

  let travelPlans = {
    destination: 'DC',
    monday: {
      location: 'National Mall',
      budget: 200,
      host: null
    }
  }
  // 等价于 let res = travelPlans && travelPlans.monday && travelPlans.monday.location
  let res = travelPlans?.monday?.location;
  // 判断对象travelPlans下的 monday 下的有没有person属性,如果没有就设置为默认值
  let res2 = travelPlans?.monday?.person
  let res3 = travelPlans?.monday?.person ?? '张三';
  console.log(res) // National Mall
  console.log(res2) // undefined
  console.log(res3) // 张三

 vue中支持可选链

1.安装依赖(Babel)

npm install --save-dev @babel/plugin-proposal-optional-chaining

2.添加至项目.babel.config.js文件中:

module.exports = {
  presets: [],
  plugins: ['@babel/plugin-proposal-optional-chaining']
}
原文地址:https://www.cnblogs.com/ronle/p/15778044.html