双重for循环简化
作者:互联网
开发bug时,总会遇到双重for循环的事
直接用for循环感觉会感到臃肿,所以一直想找一个简化的方法
举个栗子:
有两个数组,当想取出它们相同项的id值
let permission = [ {id:1}, {id:2}, {id:3} ] let menuList = [ {id:1}, {id:4}, {id:5}, {id:6} ]
普通双重循环:
let saveData = [] for (let i = 0; i < permission.length; i++) { for (let j = 0; j < menuList.length; j++) { if(permission[i].id == menuList[j].id) saveData.push(permission[i].id) } } console.log(saveData,'saveData');
简化循环:
const temp = permission.reduce((r,v) => (r[v.id] = true,r),{}) let aaa = menuList.filter(v => temp[v.id]).map(v => v.id)
再次简化:
const permissionId = permission.filter(v => menuList.some(s => v.id == s.id)).map(r => r.id)
是不是一下子清晰(高端)了许多?
当然,我是写不出这种质量的代码的,以上是思否大佬的代码,我搬过来的...
标签:permission,双重,menuList,循环,let,saveData,简化,id 来源: https://www.cnblogs.com/vokiinnn/p/15218164.html