理解 TypeScript 中的问号、冒号和未定义

pok*_*kly 3 syntax typescript angular

我对角度和打字稿很陌生,并试图了解此方法中到底发生了什么:

    updatePostcode() {
    this.FilterService.updatePostcode({

      postcode: this.regionFormGroup.get('hasPostcode').value ? 
      this.regionFormGroup.get('postcode').value : undefined

    })

    this.regionFormGroup.get('postcode').reset()
  }
Run Code Online (Sandbox Code Playgroud)

好的,这是更新邮政编码的方法。

  • 问号是什么意思?
  • “邮政编码”设置为this.regionFormGroup.get('hasPostcode').value
  • 冒号和 是什么undefined意思?( : undefined)

问题是,如果调用 updatePostcode 方法,表单将被重置,并且用户输入的邮政编码将被替换为任何内容。

小智 6

this.regionFormGroup.get('hasPostcode').value ? this.regionFormGroup.get('postcode').value : undefined
Run Code Online (Sandbox Code Playgroud)

这是一个条件(三元)运算符。问号之前是条件(this.regionFormGroup.get('hasPostcode').value),如果条件为真,则选择问号之后的值,this.regionFormGroup.get('postcode').value否则选择undefined

您可以通过以下链接阅读有关三元运算符的更多信息

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator