如何在JavaScript模板字符串中隐藏无值的${this.queryqb4ojoinAfd}?
模板字符串中实现条件渲染的方案
当然可以实现,直接在模板字符串里用短路逻辑或者三元表达式就能搞定,两种方案任选:
方案一:短路或运算(简洁版)
适合大部分场景,当目标变量为空、undefined、null这类假值时,自动替换为空字符串,不会在最终的SQL里留下多余内容:
query = `${prefix} Select ${this.arrmeasureGabung} ${this.arrdimensionkey} ${this.arrdimatribut} where{ ?obs rdf:type qb:Observation ; ${this.arrquerymeasuregabung} ${this.querydimensiongabung}. ${this.queryqb4ogabungAfd || ''} ${this.queryqb4ogabungBlck} }`
方案二:三元表达式(严谨版)
如果需要区分变量是0这类合法值和真正的空值,用三元表达式更精准,只有当变量确实有有效内容时才渲染:
query = `${prefix} Select ${this.arrmeasureGabung} ${this.arrdimensionkey} ${this.arrdimatribut} where{ ?obs rdf:type qb:Observation ; ${this.arrquerymeasuregabung} ${this.querydimensiongabung}. ${this.queryqb4ogabungAfd ? this.queryqb4ogabungAfd : ''} ${this.queryqb4ogabungBlck} }`
内容的提问来源于stack exchange,提问作者TimotyDev_03
相关产品推荐
相关产品推荐

