代码审核中出现的问题,随笔记录
在弹窗页面需要处理数据时,能用少量循环解决的问题尽量不用多次if,提高性能。
如上问题,进行代码优化为下:
方案一: 可以将map方法改为forEach方法,同时在循环时,将对应的部门和用户数据push到各自的数组中,
let regionList = [] // 部门会签节点 -部门数据
let userList = [] // 部门会签节点 -用户数据
this.dataForm.selectForm.forEach(item=>{
regionList.push(item.region)
userList.push(item.name)
})
方案二: 可以使用 Array.prototype.reduce() 方法对代码进行优化,减少遍历数组的次数,如下所示:
let [regionList, userList] = this.dataForm.selectForm.reduce((acc, item) => {
acc[0].push(item.region)
acc[1].push(item.name)
return acc
}, [[], []])
此代码使用 reduce() 方法,将部门和用户数据遍历一次,将结果存储在两个数组中并返回。其中 acc
参数是一个数组,包含两个元素,分别对应累加器中的部门和用户数据,初始化值为一个空数组的二元组 [[ ], [ ]]
,item
参数是 selectForm 数组中的元素。每次迭代时,使用 push() 方法将 item.region 和 item.name 添加到累加器数组中。最终,reduce() 方法返回累加器数组,解构后分别赋值给 regionList
和 userList
变量。