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

如何计算对象中带括号字符串的内外数字总和?已有部分实现

完整实现方案

没问题,我来帮你补全这个计算逻辑!你之前的写法是逐个处理每个count属性,灵活性不足,我们可以改成遍历所有属性值的方式,同时计算括号外和括号内的数字总和,代码更通用也更易维护。

完整代码实现(TypeScript版本)

// 调用示例
let totalResult = this.getTotal(this.count);

public getTotal(count: { [key: string]: string }): string {
  // 初始化两个累加变量,分别存储括号外和括号内的数字总和
  let outerTotal = 0;
  let innerTotal = 0;

  // 遍历count对象的所有值(无需关心具体有多少个countX属性)
  Object.values(count).forEach(itemStr => {
    // 提取括号外的数字:匹配字符串开头的连续数字
    const outerNumMatch = itemStr.match(/^\d+/);
    if (outerNumMatch) {
      outerTotal += parseInt(outerNumMatch[0], 10);
    }

    // 提取括号内的数字:匹配括号包裹的连续数字,捕获组提取核心数字
    const innerNumMatch = itemStr.match(/\((\d+)\)/);
    if (innerNumMatch) {
      innerTotal += parseInt(innerNumMatch[1], 10);
    }
  });

  // 拼接成期望的结果格式返回
  return `${outerTotal} (${innerTotal})`;
}

代码逻辑说明

  • 遍历所有值:用Object.values(count)获取所有count属性的字符串值,后续新增count5、count6这类属性时,代码无需修改就能自动兼容。
  • 正则提取数字:
    • /^\d+/精准匹配字符串开头的连续数字(即括号外的部分),比如从"250 (220)"中提取"250"。
    • /\((\d+)\)/匹配括号包裹的数字,通过捕获组(\d+)直接提取括号内的核心数字,比如从"250 (220)"中提取"220"。
  • 累加与返回:分别累加两类数字,最后用模板字符串拼接成"总和 (括号内总和)"的格式返回。

纯JavaScript版本(去掉类型注解)

// 调用示例
let totalResult = this.getTotal(this.count);

function getTotal(count) {
  let outerTotal = 0;
  let innerTotal = 0;

  Object.values(count).forEach(itemStr => {
    const outerNumMatch = itemStr.match(/^\d+/);
    if (outerNumMatch) {
      outerTotal += parseInt(outerNumMatch[0], 10);
    }

    const innerNumMatch = itemStr.match(/\((\d+)\)/);
    if (innerNumMatch) {
      innerTotal += parseInt(innerNumMatch[1], 10);
    }
  });

  return `${outerTotal} (${innerTotal})`;
}

这样调用后,totalResult就会得到你想要的"625 (520)"啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:06:58