Map和数组的对比 let map = new Map() let array = [] // 增 map.set(‘t‘, 1) array.push({t: 1}) console.log(‘add‘, map, array) // 查 let mapExist = map.has(‘t‘) let arrayExist = array.find(item => item.t) console.log(‘get‘, mapExist, arrayExist) // 改 map.set(‘t‘, 2) array.forEach(item => { item = item.t ? item.t = 2 : ‘‘ return item }) console.log(‘modify‘, map, array) // 删 map.delete(‘t‘) array.splice(array.findIndex(item => item.t), 1) console.log(‘remove‘, map, array) set和数组的对比 let set = new Set() let array = [] // 增 set.add({t: 1}) array.push({t: 1}) console.info(‘add‘, set, array) // 查 let setExist = set.has({t: 1}) let arrayExist = array.find(item => item.t) console.info(‘get‘, setExist, arrayExist) // 改 set.forEach(item => { item = item.t ? item.t = 2 : ‘‘ return item }) array.forEach(item => { item = item.t ? item.t = 2 : ‘‘ return item }) console.info(‘modify‘, set, array) // 删 set.forEach(item => { item = item.t ? set.delete(item) : ‘‘ return item }) array.splice(array.findIndex(item => item.t), 1) console.info(‘delete‘, set, array) map、set和对象的使用比较 let item = {t: 1} let map = new Map() let set = new Set() let obj = {} // 增 map.set(‘t‘, 1) set.add(item) obj.t = 1 console.log(‘add‘, map, set, obj) // 查 console.info({ action: ‘get‘, mapExist: map.has(‘t‘), setExist: set.has(item), objExist: ‘t‘ in obj }) // 改 map.set(‘t‘, 2) item.t = 2 obj.t = 2 console.log(‘modify‘, map, set, obj) // 删 map.delete(‘t‘) set.delete(item) delete obj.t console.log(‘remove‘, map, set, obj)
原文地址:https://www.cnblogs.com/ronle/p/11494891.html
时间: 2024-10-15 15:02:10