1:平常的操作 (直接同for循环)
let a = [{
id: '1',
name: '1'
}, {
id: '2',
name: '2'
}, {
id: '3',
name: '2'
}]
let b = [{
id: '3',
name: '3'
},
{
id: '1',
name: '1'
}
]
let c = [] //定义一个接受相同数组的数组
let num = 0
for (let item of a) {
num++
for (let items of b) {
num++
if (a.id == b.id) {
c.push(item)
console.log(num)
break
}
}
}
这个要算6次才能算出来
2:用map去计算
let a = [{ id: '1', name: '1' }, { id: '2', name: '2' }, { id: '3', name: '3' }] let b = [{ id: '3', name: '3' }, { id: '1', name: '1' } ] let c = new Map() a.map(item => { c.set(item.id, item) }) let d = [] let e = [] let num = 0 b.map(item => { num++ if (c.has(item.id)) { d.push(item) console.log(num) } else { e.push(item) } })
这个才计算两次