多个独立的forEach循环, 内部处理条件是一样,代码优化方案

工作中遇到了一个问题,多个独立的 forEach 循环, 内部处理条件是一样,于是乎就写出了这样子的一段代码:

第一阶段: 最Low的实现方式
      value.logo.forEach(v => {
        v.size = v.response.file.iSize,
        v.imgKey = v.response.file.sKey,
        v.imgExt = v.response.file.sExt,
        v.channel = 1
      });

      value.licensePics.forEach(v => {
        v.size = v.response.file.iSize,
        v.imgKey = v.response.file.sKey,
        v.imgExt = v.response.file.sExt,
        v.channel = 1
      });

      value.identityPic.forEach(v => {
        v.size = v.response.file.iSize,
        v.imgKey = v.response.file.sKey,
        v.imgExt = v.response.file.sExt,
        v.channel = 1
      });

上面的代码看起来很冗余,因为每个forEach里面都有相同的代码。所以我进行这样子的优化:


第二阶段: 升级的实现方式

在最外面定义了一个函数:

let  getPictures = (v) => {
  v.size = v.response.file.iSize
  v.imgKey = v.response.file.sKey
  v.imgExt = v.response.file.sExt
  v.channel = 1
}

然后调用的时候,每次讲要遍历的值传递给一个公共的函数进行处理~ 代码如下:

value.logo.map((v, k) => {
   getPictures(v)
 })

 value.licensePics.map((v, k) => {
   getPictures(v)
 })

 value.identityPic.map((v, k) => {
   getPictures(v)
 })

第三阶段: 采用ES6继续升级的实现方式
if (param.logo && param.logo.length) {
 param.logo = param.logo.map(pic => getPictures(pic));
}

if (param.licensePics && param.licensePics.length) {
 param.licensePics = param.licensePics.map(pic => getPictures(pic));
}

if (param.identityPic && param.identityPic.length) {
 param.identityPic = param.identityPic.map(pic => getPictures(pic));
}

判断数组是否为空,做兼容处理。

假设数组里面有 iSize, sKey, sExt 三个字段:

let  getPictures = (v) => {
  let { iSize, sKey, sExt } = v.response.file;
  return { 
    size: iSize, 
    imgKey: sKey, 
    imgExt: sExt,  
    channel: 1 };
}

采用ES6的赋值方式来进行赋值~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值