Set 和 Map 数据结构

时间:2017-12-08 17:47:50   收藏:0   阅读:391

set 它类似于数组,但是成员的值都是唯一的,没有重复的值。

方法:add(),has(),delete(),clear()

 

转为对像:

const items = new Set([1, 2, 3, 4, 5]);
const array = Array.from(items);

 

去除数组重复成员:

function dedupe(array) {
  return Array.from(new Set(array));
}

dedupe([1, 1, 2, 3]) // [1, 2, 3]

遍历:

const items = new Set([1, 2, 3, 4, 5]);
items.forEach((val)=>{
	console.log(val)
})

数组操作:

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}

// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

  

 

 

Map

原文:http://www.cnblogs.com/fm060/p/8006376.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!