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

JavaScript中forEach循环内多if条件不编写单独方法的最简写法

代码简化实现方案

核心思路是把重复处理逻辑的属性名统一存到数组遍历执行,单独处理inputValues的特殊映射逻辑,无需额外抽独立方法,简化后代码如下:

this.cfData.customAttributes.forEach(currentObj => {
  // 单独处理inputValues的特殊映射逻辑
  if (currentObj.inputValues !== null) {
    currentObj.inputValues = Array.prototype.map.call(currentObj.inputValues, item => item.value).join(", ");
  }
  // 批量处理需要首字母大写转换的属性
  const formatFields = ['objectType', 'dataType', 'isGridEligible', 'isInvoiceEligible']
  formatFields.forEach(key => {
    if (currentObj[key] !== null) {
      currentObj[key] = currentObj[key].toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase())
    }
  })
})

优化说明

  • 消除了4段完全重复的判断和字符串转换逻辑,整体代码精简近50%
  • 后续如果需要新增同格式转换规则的属性,只需要往formatFields数组里追加属性名即可,可维护性更高
  • 完全保留原有业务逻辑的判断规则,没有修改业务执行结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:15:02