工作中遇到了一个问题,多个独立的 forEach 循环, 内部处理条件是一样,于是乎就写出了这样子的一段代码:
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)
})