You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17:如何在条件判断中嵌套数量判断实现字符串拼接

解决方案

你可以通过嵌套三元运算符或者更清晰的分支语句实现需求,同时兼顾quantity可选属性的边界情况,以下是具体实现:

简洁版(嵌套三元运算符)

const desc = this.monthly?.label 
  ? (this.monthly.quantity && this.monthly.quantity > 1 
      ? `${this.monthly.quantity} ${this.monthly.label}` 
      : this.monthly.label) 
  : 'No label';

易读版(if-else分支)

如果觉得嵌套三元不够直观,也可以拆成分支结构:

let desc: string;
if (!this.monthly?.label) {
  desc = 'No label';
} else {
  const shouldShowQuantity = this.monthly.quantity && this.monthly.quantity > 1;
  desc = shouldShowQuantity ? `${this.monthly.quantity} ${this.monthly.label}` : this.monthly.label;
}

逻辑说明

  1. 保留原有核心判断:先检查this.monthly?.label是否存在,不存在则显示No label
  2. 当label存在时,额外判断:
    • 仅当quantity存在且数值大于1时,才拼接数量与标签
    • 若quantity未定义、等于1或小于1,直接显示原标签

内容的提问来源于stack exchange,提问作者Tali Hkan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:20:14