日常小记

122 阅读1分钟
watch: {
    feeWayInfo (val, index) {
      const feeWayVal = this.feeWay[val].value   //会引发错误,不建议此类写法。
      const feeWayVal = this.feeWay[val]?.value   // "?." es2020 引入的“链判断运算符”
  },
  

上方用到的?.直接在链式调用的时候判断,左侧的对象是否为nullundefined。如果是的,就不再往下运算,而是返回undefined

  • null 判断运算符
        var payEnd = this.queryInfo.payEnd  || ''
        var recStart = this.queryInfo.recStart  || ''
        var recEnd = this.queryInfo.recEnd  || ''

上面的三行代码都通过||运算符指定默认值,但是这样写是错的。开发者的原意是,只要属性的值为nullundefined,默认值就会生效,但是属性的值如果为空字符串或false0,默认值也会生效。

        var payEnd = this.queryInfo.payEnd  ?? ''
        var recStart = this.queryInfo.recStart  ?? ''
        var recEnd = this.queryInfo.recEnd  ?? ''

ES2020 引入了一个新的 Null 判断运算符??。它的行为类似||,但是只有运算符左侧的值为nullundefined时,才会返回右侧的值。 与逻辑运算符一起使用括号确认优先级,不然会报错。