前端老生

ES6 中Set的使用场景 - 交集、并集、差集

Set

ES6提供了Set数据结构,类似于数组,存储的元素都是唯一的,这里的唯一指的是他们存储的内存位置是唯一。

属性:size

方法:

  • clear()
  • has(ele)
  • add(ele)
  • delete(ele)

遍历器:

  • forEach
  • keys
  • values
  • entries

使用场景

集合的概念。数组去重、交集、并集、差集。

// 数组去重

let arr = [1, 1, 2, 2, 3];

let unique = [... new Set(arr)];
 

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

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

// 并集

let union = [...new Set([...a, ...b])];

// 交集

let intersect = [...new Set([...a].filter(x => b.has(x)))];

// 差集

let difference = Array.from(new Set([...a].filter(x => !b.has(x))));

// 数组 es7 array includes()

let difference = a.concat(b).filter(v => !b.includes(v));

注意:

由于Set中元素的独一无二,根据内存地址来进行判断,所以如果有多个元素是引用型的话,尽管值相同,但是内存地址不同,那么在Set对象中也将会存储多份,和Map类似

 

与Map的区别:

Map数据结构,它类似于对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值,包括对象都可以当作键。
Map结构提供了 值-值 的对应,是一种更完善的Hash结构实现。
Map的数据形式是一个二维数组,一种红黑树的数据结构,键是唯一的。
 

Map对象的键为应用类型的时候,例如键为一个Array对象,在这样的场景下,Map只有对同一个对象的引用,才将其视为同一个键,也就是根据内存来寻址的,例如如下例子,set和get的键表面上是同一个值,但是实际上存放的内存不一样,所以get返回undefined。

let m = new Map();

m.set([], 1);

m.get([]);  // 返回值为 undefined

Map与Object区别 :

Object结构提供了 字符串-值 的对应

 

说明:

扩展运算符 ... 主要用于数组的合并,被合并数组元素个数不能太大,大致是 100, 000个会有问题

Using push.apply and other .apply based methods fail when the array that we are appending is large (tests show that for me large is > 150,000 entries approx in Chrome, and > 500,000 entries in Firefox). You can see this error occurring in this jsperf.

An error occurs because the call stack size is exceeded when 'Function.prototype.apply' is called with a large array as the second argument. (MDN has a note on the dangers of exceeding call stack size using Function.prototype.apply - see the section titled "apply and built-in functions".)