工作中遇到了一个问题,多个独立的 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的赋值方式来进行赋值~