.forEach((v,i)=>
时间: 2023-11-22 21:55:15 浏览: 30
这是JavaScript中的Array原型方法之一,用于遍历数组中的每个元素并执行一个回调函数。其中,回调函数有两个参数:当前元素的值和它的索引。这个方法可以用于代替for循环,使代码更加简洁。例如:
```
const arr = [1, 2, 3];
arr.forEach((value, index) => {
console.log(`第${index}个元素是${value}`);
});
// 输出:
// 第0个元素是1
// 第1个元素是2
// 第2个元素是3
```
相关问题
async function confirm() { isShow.value = false; // params.value.pageSize = 7 let i = menu.value.find((v) => v.isActive === true).id - 1; if (i === 0) { params.value.houseType = tagsList.value.find( (v) => v.isActive === true )?.value; } else if (i === 1) { params.value.orientation = tagsList.value.find( (v) => v.isActive === true )?.value; } else if (i === 2) { params.value.rentStr = tagsList.value.find( (v) => v.isActive === true )?.value; } else if (i === 3) { let arr = []; tagsList.value?.forEach((v) => { if (v.isActive === true) { arr.push(v.value * 1); } }); if (arr.length > 0) { params.value.houseLabels = arr.join(","); } } search(); }优化
可以将这段代码优化为:
```
isShow.value = false;
// params.value.pageSize = 7
const i = menu.value.findIndex(v => v.isActive) - 1;
if (i === 0) {
params.value.houseType = tagsList.value.find(v => v.isActive)?.value;
} else if (i === 1) {
params.value.orientation = tagsList.value.find(v => v.isActive)?.value;
} else if (i === 2) {
params.value.rentStr = tagsList.value.find(v => v.isActive)?.value;
} else if (i === 3) {
const arr = tagsList.value?.filter(v => v.isActive)?.map(v => v.value * 1);
if (arr?.length) {
params.value.houseLabels = arr.join(",");
}
}
search();
```
这样可以将代码变得更加简洁和易读,同时也可以避免使用可选链操作符时的一些潜在问题。
强化并优化一下代码 const list = await store.dispatch('user/getMenuRole') const menuList = [] let hiddenMenuList = null for (let i = 0; i < list.length; i++) { const item = list[i] if (item.hidden) { for (let index = 0; index < hiddenList.length; index++) { const vmItme = hiddenList[index] const childrenData = [] vmItme.children.forEach((v, vIndex) => { item.children.forEach(s => { if (v.name === s.meta.menuName) { s.meta.childrenBtnList.length > 0 && ( v.meta.childrenBtnList = s.meta.childrenBtnList ) childrenData.push(v) const routerList = vmItme routerList.children = childrenData hiddenMenuList = routerList } }) }) } } else { menuList.push(item) } }
下面是进一步强化并优化后的代码:
```
const list = await store.dispatch('user/getMenuRole')
const menuList = []
const hiddenMenuList = []
for (const item of list) {
if (item.hidden) {
const childrenData = hiddenList.flatMap(vmItme => {
const children = vmItme.children.filter(v => item.children.some(s => v.name === s.meta.menuName))
children.forEach(v => {
const s = item.children.find(s => v.name === s.meta.menuName)
if (s.meta.childrenBtnList.length > 0) {
v.meta.childrenBtnList = s.meta.childrenBtnList
}
})
vmItme.children = children
return vmItme
})
hiddenMenuList.push(...childrenData)
} else {
menuList.push(item)
}
}
```
这里使用了 `Array.prototype.flatMap()` 和 `Array.prototype.some()` 方法代替了嵌套的循环逻辑,使代码更加简洁易读。同时,使用扩展运算符 `...` 将数组展开,避免了多余的赋值操作。