优化这段代码 lotLocInvs.forEach(res=>{ if(!haveData.includes(res.lot.code)){ finallyData.push(res) haveData.push(res.lot.code) } })
时间: 2024-01-30 14:02:00 浏览: 24
可以尝试使用 Set 数据结构来优化这段代码,避免使用 includes 方法导致的性能问题,示例代码如下:
```
const haveData = new Set()
lotLocInvs.forEach(res => {
if (!haveData.has(res.lot.code)) {
finallyData.push(res)
haveData.add(res.lot.code)
}
})
```
使用 Set 数据结构可以快速判断某个元素是否存在,避免了数组的线性查找。这样可以提高代码的执行效率。
相关问题
帮我优化一下 下面的代码 _list.forEach(item=>{ item.child.forEach(i=>{ i.forEach(k=>{ if (k.id === id) { dropData = k } }) }) }) _list.forEach(item => { item.child.forEach(val=>{ val.forEach(k=>{ if (k.timetableInputId === dropData.timetableInputId && k.sequence === dropData.sequence && k.week === dropData.week && +k.classPeriodType === 4 ) { k.classId = item.id dropDataPackage.push(k) } }) }) })
可以将上述代码进行优化,通过使用 Array 的内置方法,例如 `find` 和 `filter` 等,可以提高代码的可读性和执行效率。下面是一个可能的优化版本:
```
const dropData = _list.flatMap(item => item.child.flat().find(i => i.some(k => k.id === id)))
if (dropData) {
const dropDataPackage = _list.flatMap(item => item.child.flat().filter(val => val.some(k => k.timetableInputId === dropData.timetableInputId && k.sequence === dropData.sequence && k.week === dropData.week && +k.classPeriodType === 4)).map(k => { k.classId = item.id; return k }))
}
```
优化后的代码使用了 `flatMap` 和 `find` 方法来查找匹配的 `dropData` 对象,使用 `flatMap` 和 `filter` 方法来查找匹配的 `dropDataPackage` 数组,并使用 `map` 方法将 `classId` 添加到匹配的对象中。
优化这段代码 res.data.availablePlayItemVoList.forEach((item: any) => { this.playDateProductInfoList.forEach((v: any) => { v.playScreeningList.forEach((items: any) => { if (items.playItemCode == item.playItemCode) { this.$set( items, "availableTotal", item.availableTotal != null ? item.availableTotal : null ); } if (item.screeningList.length > 0) { item.screeningList.forEach((itemA: any) => { if (items.sysTimeQuantumList != null) { items.sysTimeQuantumList.forEach((itemB: any) => { if (itemA.screeningCode == itemB.screeningCode) { this.$set( itemB, "surplusTotal", itemA.surplusTotal != null ? itemA.surplusTotal : null ); } }); } }); } }); }); }); });
这段代码也可以使用ES6的数组方法进行优化,如下所示:
```javascript
res.data.availablePlayItemVoList.forEach(item => {
this.playDateProductInfoList.forEach(v => {
v.playScreeningList.filter(items => items.playItemCode === item.playItemCode)
.forEach(items => {
this.$set(
items,
"availableTotal",
item.availableTotal != null ? item.availableTotal : null
);
item.screeningList.forEach(itemA => {
if (items.sysTimeQuantumList != null) {
items.sysTimeQuantumList.filter(itemB => itemA.screeningCode === itemB.screeningCode)
.forEach(itemB => {
this.$set(
itemB,
"surplusTotal",
itemA.surplusTotal != null ? itemA.surplusTotal : null
);
});
}
});
});
});
});
```
同样地,使用`filter`方法可以减少循环嵌套,使代码更加清晰易读。另外,可以使用ES6的箭头函数来简化代码。