ES6(十)map、set与数组和对象的比较
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)
示例
let json1 = {"name":"ES6","day":"2014","feature":"新特性"}; //json 2 map let map1 = new Map(); for(let i in json1){ map1.set(i,json1[i]); } console.log(map1); //map 2 json let map = new Map(); map.set("name","ES6"); map.set("day","2014"); map.set("feature","新特性"); let json = {}; for(let [k,v] of map){ json[k]=v; } console.log(json); const num = 1000000; let a = {}; for(let i = 0;i<num;i++){ a[`element${i}`]=i; } let start_time = new Date(); for(let key in a){ a[key]+=1; } let end_time = new Date(); console.log("time cost:",end_time-start_time); const num = 1000000; let a = new Map(); for(let i = 0;i<num;i++){ a.set(`element${i}`,i); } let start_time = new Date(); for(let key of a.keys()){ a.set(key,a.get(key)+1); } let end_time = new Date(); console.log("time cost:",end_time-start_time);
循环方式
projectMap.forEach(function (value, key, map) { //value和key就是map的key,value,map是map本身 });
去重
let arr = [4, 1, 3, 3, 2, '2']; let uniqueArr = [...new Set(arr)]; console.log(uniqueArr); // [4, 1, 3, 2, "2"]
that.dataInfo = [...new Set(that.dataInfo.concat([], res.data.data.result))] let newArr = Array.from(that.dataInfo) console.log(newArr)
转换
// map转object let obj= Object.create(null); for (let[k,v] of map) { obj[k] = v; }
// object转json JSON.stringify(obj);